Is there a way to round a decimal place to the nearest whole in javascript?
I have a number with decimal places and I am wondering if it'开发者_JS百科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
Use Number.toFixed(number of decimal places):
var num = 4.59;
var rounded = num.toFixed(1);
Use the toFixed()
method.
More detailed information at: MDN :: toFixed
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.
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);
精彩评论