你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
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}}
:)
其他回答
es6接受答案版本:
function round(value, precision) {
const multiplier = 10 ** (precision || 0);
return Math.round(value * multiplier) / multiplier;
}
我投票给toFixed(),但是,为了记录,这里有另一种使用位移位将数字转换为int的方法。因此,它总是趋近于零(正数向下,负数向上)。
var rounded = ((num * 10) << 0) * 0.1;
但是,嘿,因为没有函数调用,它非常快。:)
这里有一个使用字符串匹配:
var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
我不建议使用字符串变体,只是说。
const solds = 136780000000;
const number = (solds >= 1000000000 && solds < 1000000000000) ? { divisor: 1000000000, postfix: "B" }: (solds >= 1000000 && solds < 1000000000) ? { divisor: 1000000, postfix: "M" }: (solds >= 1000 && solds < 1000000) ? { divisor: 1000, postfix: "K" }: { divisor: 1, postfix: null };
const floor = Math.floor(solds / number.divisor).toLocaleString();
const firstDecimalIndex = solds.toLocaleString().charAt(floor.length+1);
const final =firstDecimalIndex.match("0")? floor + number.postfix: floor + "." + firstDecimalIndex + number.postfix;
console.log(final);
136780000000 --> 136.7B
1367800 --> 1.3M
1342 --> 1.3K
为什么不干脆
let myNumber = 213.27321;
+myNumber.toFixed(1); // => 213.3
toFixed: 返回使用定点表示法表示给定数字的字符串。 一元加号(+):一元加号运算符位于其操作数之前,求值为其操作数,但尝试将其转换为数字(如果它还不是数字)。
Lodash有一个循环方法:
_.round(4.006);
// => 4
_.round(4.006, 2);
// => 4.01
_.round(4060, -2);
// => 4100
文档。
源。