开发者

Is there a way to round a decimal place to the nearest whole in javascript?

开发者 https://www.devze.com 2023-03-28 09:11 出处:网络
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?

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 0s 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号