0

So this code adds up by 0.001 on each loop, i have it set to only show me 3 numbers past the decimal but on the 10th loop for example when it reaches 0.01 i want it to only show 2 numbers past the decimal, i dont need it to show the 0.

var Num = 0.000
for(s = 1; s <= 15; s++){
Num = Num + 0.001
var NumX = Num.toFixed(3)
if(NumX % 10 == 0){
var NumX = Num.toFixed(2)
alert("working")
}

}

I tried dividing by 10 in the above code but i dont know how to divide decimals can someone show me how to get this code to work, thanks.

Matt
  • 163
  • 1
  • 11
  • 1
    You can check out answers here http://stackoverflow.com/questions/19715819/divide-number-with-decimals-javascript – Akinjide Jan 08 '17 at 01:18
  • So when it reaches 0.011, you want it to show 0.01? – numbermaniac Jan 08 '17 at 01:18
  • If you can, avoid computation with floating point values. You might not get the expected result due to precision errors. Why not use whole numbers? – Felix Kling Jan 08 '17 at 01:28
  • @numbermaniac No only when it reaches a number like 0.20 where the 3rd number after decimal would be a 0. – Matt Jan 08 '17 at 01:31

1 Answers1

0

You could use

var NumX = Num.toFixed( s%10==0 ? 2 : 3 );

That is, decide how many decimal places to show based on the value of s.

Scott Hunter
  • 44,196
  • 8
  • 51
  • 88