Boriel Basic Forum
Rounding float numbers to 2 decimal places - Printable Version

+- Boriel Basic Forum (https://forum.boriel.com)
+-- Forum: Compilers and Computer Languages (https://forum.boriel.com/forumdisplay.php?fid=12)
+--- Forum: ZX Basic Compiler (https://forum.boriel.com/forumdisplay.php?fid=11)
+---- Forum: How-To & Tutorials (https://forum.boriel.com/forumdisplay.php?fid=13)
+---- Thread: Rounding float numbers to 2 decimal places (/showthread.php?tid=2537)



Rounding float numbers to 2 decimal places - rbiondi - 2023-12-29

Hello,

I need to round or at least truncate a Float variable to 2 decimal places.
Do you know how this could be accomplished since there's no ROUND function?

Thank you very much,
Rogerio


RE: Rounding float numbers to 2 decimal places - boriel - 2023-12-30

There is a trick for that which can be accomplished in several ways. Here's an example of a ROUND function (explained in the ZX Spectrum Manual):

Code:
FUNCTION Round(n as Float, decimals as UByte = 0) AS Float
  DIM tmp as Float
  DIM d10 = 10^decimals
  IF n >= 0 THEN
    LET tmp = INT(n * d10 + 0.5)
  ELSE
    LET tmp = INT(n * d10 - 0.5)
  END IF
  RETURN tmp / d10
END FUNCTION
This function will round towards +/- infinity.
Use with Round(number, digits)

I'll include it in the math library.


RE: Rounding float numbers to 2 decimal places - rbiondi - 2023-12-31

Thank you very much!

A sugestion would be adding an optional parameter to str$ function:

Code:
dim floatnum as Float = 0.135[/font][/size][/color]
print str$(floatnum, 2)


>> prints 0.13