问题
I have a number with decimal places and I am wondering if it's possible to round the decimal to the nearest whole using javascript?
My number is: 4.59
I need my number to round to: 4.60
回答1:
Use Number.toFixed(number of decimal places):
var num = 4.59;
var rounded = num.toFixed(1);
回答2:
Use the toFixed()
method.
More detailed information at: MDN :: toFixed
回答3:
var x = 4.5678;
Math.round(x * 10) / 10; // 4.6
Math.round(x * 100) / 100; // 4.57
Where the number of 0
s of multiplication and division is the decimal point you are aiming for.
回答4:
I propose you do what Daff suggests, but if you want the trailing "0", you will need to add it onto the string:
var num = 4.59;
var rounded = num.toFixed(1) + '0';
Also, if you want the number as a number rather than a string, use:
Math.round(num * 10);
As Emil suggested. If you then want to display it with the trailing 0, do:
Math.round(num * 10).toFixed(2);
来源:https://stackoverflow.com/questions/7066110/is-there-a-way-to-round-a-decimal-place-to-the-nearest-whole-in-javascript