views:

277

answers:

3

I'm doing some calculation with numbers and would like to only print an integer (the number without the decimals).

I thought that the toFixed() method of the Number class would do the trick, and it does most of the time. But quite frequently strange values are returned. Here are 2 examples:

  • Number(0.002).toFixed(0) returns "0." while Number(1.002).toFixed(0) returns "1" (without the period)

  • Once in a while, Number(0.002).toFixed(0) returns "1"

Needless to say that's not the expected behaviour. Am I not using this method correctly?

*edit: * I know I just have to do int(0.002) to get 0 but I'd like to understand that strange behaviour.

+1  A: 

I've tested both on Flex SDK 3.4 and Flex SDK 4.0 and it looks like a bug, maybe post it on bugs.adobe.com? Although I think it might be related to the Flash Player rather than Flex.

Anyway if you're trying to convert a number to a string with no decimal places you can use this as a workaround:

Math.round(theNumber).toString()

This will get rid of all the digits after the dot.

Robert Bak
thanks for testing on flex 4. I'll post a bug.Your solution however will return "1" when theNumber = 0.902 for example and I wanted "0" returned.
Guillaume Flandre
Then how about using Math.floor() instead of Math.round()
Christophe Herreman
Right, Math.floor, thanks for the correction, absent-mindedness will be the end of me.
Robert Bak
+3  A: 

This is a known bug. The unsexy workaround is to use either use Math.round() or just checking the returned string for that trailing period.

See bug report on JIRA here: http://bugs.adobe.com/jira/browse/FP-1595

grapefrukt