I need to limit the precision of a number dynamically depending of its size. I mean, if I have 8903.234 I want it without decimal numbers (8903), if I have 849342.23 I want it ending with 2 zeros (849300) or if I want 6.589654 I want it rounded to 3 decimals (6.589).

Anyone with an idea of how to implement this? (The scale is not decided yet but will be linear)

Edit: to write it better, the larger the number the less precision I want.

Have you looked at the different numeric format strings?
–
Oded♦Nov 6 '11 at 22:23

2

So the larger the number gets the less precision you want to get? Then larger still numbers get their hundredths rounded?
–
Jeremy ChildNov 6 '11 at 22:24

So you only ever want, say, four digits to be reported as non-zero?
–
sarnoldNov 6 '11 at 22:27

@Jeremy: thanks for the better wording. Right, the bigger the less precission.
–
Ignacio Soler GarciaNov 6 '11 at 22:27

Beware of floating point rounding errors when you are after guaranteed precision to right of decimal points or you may find yourself tearing your hair out trying to figure out why it is not rounding quite right.
–
GilbertNov 6 '11 at 22:29

2 Answers
2

I think we're talking about "significant digits". You can use Math.log(number) to get the scale of your number, then simply substract the number of significant digits to keep, divide, round, multiply, profit!

You're right, I forgot that "Log" is the neperian log. I needed to use "Log10" to have the right one. I corrected it now. It's weird people upvoted this when it actually was broken! XD
–
Kevin CoulombeDec 2 '11 at 20:14

Sorry but this is still not working. I'm just getting the numbers at the left of the decimal point. As the question says the larger the number the less precision I want or the smaller the number the bigger the precission I need.
–
Ignacio Soler GarciaDec 3 '11 at 9:53