Limit the decimal place in JavaScript is not working in this math code? [duplicate]
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 exponen开发者_如何转开发t?
4.45678765e-6
means 4.45678765 * 10^(-6)
or 0.00000445678765
, so
4.45678765e-6 * 10000 == 0.0445678765
Math.round(0.0445678765) == 0
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))
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
精彩评论