你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
var number = 123.456;
console.log(number.toFixed(1)); // should round to 123.5
其他回答
我投票给toFixed(),但是,为了记录,这里有另一种使用位移位将数字转换为int的方法。因此,它总是趋近于零(正数向下,负数向上)。
var rounded = ((num * 10) << 0) * 0.1;
但是,嘿,因为没有函数调用,它非常快。:)
这里有一个使用字符串匹配:
var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
我不建议使用字符串变体,只是说。
如果你关心正确的四舍五入,那么:
function roundNumericStrings(str , numOfDecPlacesRequired){
var roundFactor = Math.pow(10, numOfDecPlacesRequired);
return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString(); }
否则,如果你没有,那么你已经从以前的帖子回复
str.slice(0, -1)
数学。整数(num * 10) / 10无效。
例如,1455581777.8-145558160.4会得到1310023617.3999999。
所以只使用num。tofixed (1)
Lodash有一个循环方法:
_.round(4.006);
// => 4
_.round(4.006, 2);
// => 4.01
_.round(4060, -2);
// => 4100
文档。
源。
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8