如何在Javascript中四舍五入到小数点后1位?

你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?

我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。

606599 次浏览
var num = 34.7654;


num = Math.round(num * 10) / 10;


console.log(num); // Logs: 34.8
var number = 123.456;


console.log(number.toFixed(1)); // should round to 123.5

Math.round(num * 10) / 10工作,这里有一个例子…

var number = 12.3456789
var rounded = Math.round(number * 10) / 10
// rounded is 12.3

如果你想让它有一个小数点,即使它是0,然后加…

var fixed = rounded.toFixed(1)
// fixed is always to 1 d.p.
// NOTE: .toFixed() returns a string!


// To convert back to number format
parseFloat(number.toFixed(2))
// 12.34
// but that will not retain any trailing zeros


// So, just make sure it is the last step before output,
// and use a number format during calculations!

编辑:添加圆与精度功能…

使用这个原理,作为参考,这里有一个方便的小圆函数,它需要精度…

function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}

... 使用……

round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7

... 默认舍入到最接近的整数(精度为0)…

round(12345.6789) // 12346

... 可以四舍五入到最接近的10或100等…

round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300

... 正确处理负数……

round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5

... 并且可以与toFixed结合使用,以一致的格式作为字符串…

round(456.7, 2).toFixed(2) // "456.70"

如果你的方法不起作用,请发布你的代码。

然而,你可以完成舍入任务如下:

var value = Math.round(234.567*100)/100

234.56英镑可以吗

类似的

 var value = Math.round(234.567*10)/10

会给出234.5

通过这种方式,您可以使用一个变量来代替前面使用的常量。

我投票给toFixed(),但是,为了记录,这里有另一种使用位移位将数字转换为int的方法。因此,它总是趋近于零(正数向下,负数向上)。

var rounded = ((num * 10) << 0) * 0.1;

但是,嘿,因为没有函数调用,它非常快。:)

这里有一个使用字符串匹配:

var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');

我不建议使用字符串变体,只是说。

如果你使用Math.round(5.01),你将得到5而不是5.0

如果你使用toFixed,你会遇到舍入 问题

如果你想两全其美,那就把两者结合起来:

(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 original=28.453


// 1.- round "original" to two decimals
var result = Math.round (original * 100) / 100  //returns 28.45


// 2.- round "original" to 1 decimal
var result = Math.round (original * 10) / 10  //returns 28.5


// 3.- round 8.111111 to 3 decimals
var result = Math.round (8.111111 * 1000) / 1000  //returns 8.111

不那么复杂,更容易实现……

有了这个,你可以创建一个函数来做:

function RoundAndFix (n, d) {
var m = Math.pow (10, d);
return Math.round (n * m) / m;
}

function RoundAndFix (n, d) {
var m = Math.pow (10, d);
return Math.round (n * m) / m;
}
console.log (RoundAndFix(8.111111, 3));

编辑:看这个如何四舍五入使用一半。四舍五入模式是我们大多数人在小学时学到的

这似乎对我抛出的任何东西都有效:

function round(val, multiplesOf) {
var s = 1 / multiplesOf;
var res = Math.ceil(val*s)/s;
res = res < val ? res + multiplesOf: res;
var afterZero = multiplesOf.toString().split(".")[1];
return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
}

它是四舍五入的,所以您可能需要根据用例修改它。这应该可以工作:

console.log(round(10.01, 1)); //outputs 11
console.log(round(10.01, 0.1)); //outputs 10.1

如果你关心正确的四舍五入,那么:

function roundNumericStrings(str , numOfDecPlacesRequired){
var roundFactor = Math.pow(10, numOfDecPlacesRequired);
return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString();  }

否则,如果你没有,那么你已经从以前的帖子回复

str.slice(0, -1)

完成最佳答案:

var round = function ( number, precision )
{
precision = precision || 0;
return parseFloat( parseFloat( number ).toFixed( precision ) );
}

输入参数number可能"not"总是一个数字,在这种情况下。tofixed不存在。

Math.round( num * 10) / 10不起作用。

例如,1455581777.8-145558160.4给出了1310023617.3999999

所以只使用num.toFixed(1)

lodash有一个round方法:

_.round(4.006);
// => 4


_.round(4.006, 2);
// => 4.01


_.round(4060, -2);
// => 4100

# EYZ0。

# EYZ0。

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;
}

通常,十进制舍入是通过缩放:round(num * p) / p来完成的

天真的实现

使用下面带有中间数的函数,您将得到预期的上四舍五入值,或者有时根据输入得到下四舍五入值。

舍入中的inconsistency可能会在客户端代码中引入难以检测的错误。

function naiveRound(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
return Math.round(num * p) / p;
}


console.log( naiveRound(1.245, 2) );  // 1.25 correct (rounded as expected)
console.log( naiveRound(1.255, 2) );  // 1.25 incorrect (should be 1.26)

更好的实现

通过将数字转换为指数的符号中的字符串,正数按预期四舍五入。 但是,要注意,负数四舍五入与正数不同

事实上,它执行的基本等同于规则“round half up”;,你会看到round(-1.005, 2)的计算结果是-1,即使round(1.005, 2)的计算结果是1.01lodash _。圆法使用这种技术。

/**
* Round half up ('round half towards positive infinity')
* Uses exponential notation to avoid floating-point issues.
* Negative numbers round differently than positive numbers.
*/
function round(num, decimalPlaces) {
num = Math.round(num + "e" + decimalPlaces);
return Number(num + "e" + -decimalPlaces);
}


// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // 0


// testing edge cases
console.log( round(1.005, 2) );   // 1.01
console.log( round(2.175, 2) );   // 2.18
console.log( round(5.015, 2) );   // 5.02


console.log( round(-1.005, 2) );  // -1
console.log( round(-2.175, 2) );  // -2.17
console.log( round(-5.015, 2) );  // -5.01

如果您希望在负数舍入时保持通常的行为,则需要在调用Math.round ()之前将负数转换为正数,然后在返回之前将它们转换回负数。

// Round half away from zero
function round(num, decimalPlaces) {
num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
return Number(num + "e" + -decimalPlaces);
}

有一种不同的纯数学技术可以执行舍入到最近(使用“离零的半圆”;),其中在调用舍入函数之前应用ε校正

简单地说,我们添加最小的浮动值(= 1.0 ulp;单位在最后的位置)到数字之前舍入。这将移动到数字之后的下一个可表示的值,远离零。

/**
* Round half away from zero ('commercial' rounding)
* Uses correction to offset floating-point inaccuracies.
* Works symmetrically for positive and negative numbers.
*/
function round(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
var e = Number.EPSILON * num * p;
return Math.round((num * p) + e) / p;
}


// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // -1


// testing edge cases
console.log( round(1.005, 2) );  // 1.01
console.log( round(2.175, 2) );  // 2.18
console.log( round(5.015, 2) );  // 5.02


console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02

这需要抵消在十进制数字编码期间可能出现的隐式舍入误差,特别是那些有"5"在小数点后的最后一位,比如1.005、2.675和16.235。实际上,十进制系统中的1.005编码为64位二进制浮点的1.0049999999999999;而十进制系统中的1234567.005被编码为64位二进制浮点的1234567.0049999998882413

值得注意的是,最大二进制数round-off error依赖于(1)数字的大小和(2)相对机器ε(2^-52)。

我做了一个返回数字类型,也只在需要的时候放置小数(没有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;
}

我找到了一个避免精度问题的方法:

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
Math.round( mul/count * 10 ) / 10


Math.round(Math.sqrt(sqD/y) * 10 ) / 10

谢谢

为什么不干脆

let myNumber = 213.27321;
+myNumber.toFixed(1); // => 213.3
    <李> # EYZ0: 返回一个使用定点表示法表示给定数字的字符串
  1. 一元加(+):一元加号运算符位于其操作数之前,求值为其操作数,但如果操作数还不是数字,则尝试将其转换为数字。

使用toprecprecision方法:

var a = 1.2345
a.toPrecision(2)


// result "1.2"
function rnd(v,n=2) {
return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(10,n)
}

这个很好地抓住了极端情况

如果你的源代码是typescript,你可以使用这样的函数:

public static ToFixedRounded(decimalNumber: number, fractionDigits: number): number {
var rounded = Math.pow(10, fractionDigits);
return (Math.round(decimalNumber * rounded) / rounded).toFixed(fractionDigits) as unknown as number;
}

你可以简单地做以下几点:

let n = 1.25
let result = Number(n).toFixed(1)
// output string: 1.3
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.7 b

1367800——比;1.3米

1342年,在1.3 k