你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
我投票给toFixed(),但是,为了记录,这里有另一种使用位移位将数字转换为int的方法。因此,它总是趋近于零(正数向下,负数向上)。
var rounded = ((num * 10) << 0) * 0.1;
但是,嘿,因为没有函数调用,它非常快。:)
这里有一个使用字符串匹配:
var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
我不建议使用字符串变体,只是说。
其他回答
如果你使用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);
}
我做了一个返回数字类型,也只在需要的时候放置小数(没有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;
}
我投票给toFixed(),但是,为了记录,这里有另一种使用位移位将数字转换为int的方法。因此,它总是趋近于零(正数向下,负数向上)。
var rounded = ((num * 10) << 0) * 0.1;
但是,嘿,因为没有函数调用,它非常快。:)
这里有一个使用字符串匹配:
var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
我不建议使用字符串变体,只是说。
Angular的小过滤器,如果有人想要的话:
angular.module('filters').filter('decimalPlace', function() {
return function(num, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(num * multiplier) / multiplier;
};
});
使用if via:
{{model.value| decimalPlace}}
{{model.value| decimalPlace:1}}
{{model.value| decimalPlace:2}}
:)
我找到了一个避免精度问题的方法:
function badRound (num, precision) {
const x = 10 ** precision;
return Math.round(num * x) / x
}
// badRound(1.005, 2) --> 1
function round (num, precision) {
const x = 10 ** (precision + 1);
const y = 10 ** precision;
return Math.round(Math.round(num * x) / 10) / y
}
// round(1.005, 2) --> 1.01