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

只谈情不闲聊 提交于 2019-12-04 01:34:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!