你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
如果你关心正确的四舍五入,那么:
function roundNumericStrings(str , numOfDecPlacesRequired){
var roundFactor = Math.pow(10, numOfDecPlacesRequired);
return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString(); }
否则,如果你没有,那么你已经从以前的帖子回复
str.slice(0, -1)
其他回答
我做了一个返回数字类型,也只在需要的时候放置小数(没有0填充)。
例子:
roundWithMaxPrecision(11.234, 2); //11.23
roundWithMaxPrecision(11.234, 1); //11.2
roundWithMaxPrecision(11.234, 4); //11.23
roundWithMaxPrecision(11.234, -1); //10
roundWithMaxPrecision(4.2, 2); //4.2
roundWithMaxPrecision(4.88, 1); //4.9
代码:
function roundWithMaxPrecision (n, precision) {
const precisionWithPow10 = Math.pow(10, precision);
return Math.round(n * precisionWithPow10) / precisionWithPow10;
}
数学。整数(num * 10) / 10无效。
例如,1455581777.8-145558160.4会得到1310023617.3999999。
所以只使用num。tofixed (1)
如果你使用Math.round(5.01),你将得到5而不是5.0。
如果你使用固定你会遇到舍入问题。
如果你想两全其美,那就把两者结合起来:
(Math.round(5.01 * 10) / 10).toFixed(1)
你可能想为此创建一个函数:
function roundedToFixed(input, digits){
var rounder = Math.pow(10, digits);
return (Math.round(input * rounder) / rounder).toFixed(digits);
}
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8
Lodash有一个循环方法:
_.round(4.006);
// => 4
_.round(4.006, 2);
// => 4.01
_.round(4060, -2);
// => 4100
文档。
源。