May be in the first case, the Math.round would perform its round off operation first and then multiplies.
So how can we achieve accurate rounding results?
The following statement shows 8.32, as opposed to 8.33:
Alert.show((Math.round(8.325 * 100.0) / 100.0).toString());
We're confident that there's a way a produce accurate results in Flex, however, we have yet to find it.
1 person found this helpful
Math.round is working correctly, if you trace(8.325 * 100) you'll see 832.4999999999999 because of floating point multiplication.
This post might be helpful: http://joshblog.net/2007/01/30/flash-floating-point-number-errors/
Thanks, Shongrunden - I found that same link literally a minute or two before I saw your response - after some preliminary testing, it looks like the following functions work well as a workaround:
* Corrects errors caused by floating point math.
public function correctFloatingPointError(number:Number, precision:int = 5):Number
//default returns (10000 * number) / 10000
//should correct very small floating point errors
var correction:Number = Math.pow(10, precision);
return Math.round(correction * number) / correction;
* Tests if two numbers are almost equal.
public function fuzzyEquals(number1:Number, number2:Number, precision:int = 5):Boolean
var difference:Number = number1 - number2;
var range:Number = Math.pow(10, -precision);
//0.00001 < difference > -0.00001
return difference < range && difference > -range;
If I was doing a money calculator, I'm not sure I would use Math.round(). I
think I would use toPrecision or toFixed to display the current values. I
believe most calculators keep hidden digits.
By using the CorrectFloatingPoint error function above with the following Round function, the rounding is consistent:
public function Round(numberVal:Number, roundTo:Number):Number
return CorrectFloatingPointError(Math.round(CorrectFloatingPointError(numberVal *
CorrectFloatingPointError(Math.pow(10, roundTo)))) /
However, any value passed to the Round function should also be corrected - for example:
var x:Number = Round(CorrectFloatingPoint(90.00 * .0925));