2

Possible Duplicate:
limit the decimal place in javascript is not working for 4.45678765e-6

This doesn't give me the answer I would get on a scientific calendar.

var myNum = Math.floor (4.45678765 * 10000)/10000;
document.write (x);

Is it even possible to limit the decimal places if the value has an exponent?

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253

3 Answers3

8

4.45678765e-6 means 4.45678765 * 10^(-6) or 0.00000445678765, so

4.45678765e-6 * 10000 == 0.0445678765
Math.round(0.0445678765) == 0
Alex Bagnolini
  • 21,990
  • 3
  • 41
  • 41
bjornd
  • 22,397
  • 4
  • 57
  • 73
1

4.45678765e-6 * 10000 is still less than 1 (it's 4.45678765e-2 in fact), so calling round or floor will make it 0, and dividing 0 by 10000 is still 0. In this case, you would need to multiply and divide by 10^10 to get the right answer, but that's not a general solution. One way is (in pseudocode):

counter = 0
while x < 100000:
    x = x * 10
    counter = counter + 1

x = Math.floor(x / 10)
x = x / (10 ^ (counter - 1))
Jodaka
  • 1,237
  • 8
  • 16
1

Javascript has a toPrecision function that will allow to you specify significant figures rather than decimal places.

var x = 4.45678765e-6;
console.log(x.toPrecision(4)); // 0.000004457

console.log(x.toFixed(4)); // 0.0000
Dennis
  • 32,200
  • 11
  • 64
  • 79