Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rounding float numbers to 2 decimal places
#1
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
Reply
#2
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.
Reply
#3
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
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)