四舍五入至小数点后两位(仅在必要时)

我想最多舍入小数点后两位,但仅在必要时才可以

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?

阳光Itachi村村2020/03/09 17:19:13

If you happen to already be using the d3 library, they have a powerful number formatting library: https://github.com/mbostock/d3/wiki/Formatting

Rounding specifically is here: https://github.com/mbostock/d3/wiki/Formatting#d3_round

In your case, the answer is:

> d3.round(1.777777, 2)
1.78
> d3.round(1.7, 2)
1.7
> d3.round(1, 2)
1
飞云Tom小宇宙2020/03/09 17:19:13

To not deal with many 0s, use this variant:

Math.round(num * 1e2) / 1e2
猴子卡卡西2020/03/09 17:19:13

Easiest way:

+num.toFixed(2)

It converts it to a string, and then back into an integer / float.

Harry逆天2020/03/09 17:19:13

Use something like this "parseFloat(parseFloat(value).toFixed(2))"

parseFloat(parseFloat("1.7777777").toFixed(2))-->1.78 
parseFloat(parseFloat("10").toFixed(2))-->10 
parseFloat(parseFloat("9.1").toFixed(2))-->9.1
米亚神无2020/03/09 17:19:13

Here is a prototype method:

Number.prototype.round = function(places){
    places = Math.pow(10, places); 
    return Math.round(this * places)/places;
}

var yournum = 10.55555;
yournum = yournum.round(2);
神乐路易2020/03/09 17:19:13
var roundUpto = function(number, upto){
    return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);

toFixed(2) here 2 is number of digits upto which we want to round this num.

路易飞云2020/03/09 17:19:13

It may work for you,

Math.round(num * 100)/100;

to know the difference between toFixed and round. You can have a look at Math.round(num) vs num.toFixed(0) and browser inconsistencies.

乐十三2020/03/09 17:19:13

This may help you:

var result = Math.round(input*100)/100;

for more information, you can have a look at this link

Math.round(num) vs num.toFixed(0) and browser inconsistencies

Mandy番长2020/03/09 17:19:13

If you are using lodash library, you can use the round method of lodash like following.

_.round(number, precision)

Eg:

_.round(1.7777777, 2) = 1.78
Sam蛋蛋Itachi2020/03/09 17:19:13

2017
Just use native code .toFixed()

number = 1.2345;
number.toFixed(2) // "1.23"

If you need to be strict and add digits just if needed it can use replace

number = 1; // "1"
number.toFixed(5).replace(/\.?0*$/g,'');
小小小胖2020/03/09 17:19:13

Try this light weight solution:

function round(x, digits){
  return parseFloat(x.toFixed(digits))
}

 round(1.222,  2) ;
 // 1.22
 round(1.222, 10) ;
 // 1.222
蛋蛋L西里2020/03/09 17:19:13

Use this function Number(x).toFixed(2);

阿良小哥2020/03/09 17:19:13

对我来说Math.round()没有给出正确的答案。我发现toFixed(2)效果更好。以下是这两个示例:

console.log(Math.round(43000 / 80000) * 100); // wrong answer

console.log(((43000 / 80000) * 100).toFixed(2)); // correct answer

乐米亚2020/03/09 17:19:13
+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12

(10).toFixed(2); // = 10.00
(10.12345).toFixed(2); // = 10.12
Jim前端2020/03/09 17:19:13

这是一种简单的方法:

Math.round(value * 100) / 100

您可能想继续做一个单独的功能来为您做这件事:

function roundToTwo(value) {
    return(Math.round(value * 100) / 100);
}

然后,您只需传递值即可。

您可以通过添加第二个参数来将其四舍五入为任意小数位数。

function myRound(value, places) {
    var multiplier = Math.pow(10, places);

    return (Math.round(value * multiplier) / multiplier);
}
米亚Eva2020/03/09 17:19:13

这里没有找到正确的答案@stinkycheeseman要求四舍五入,你们都四舍五入了数字。

要向上舍入,请使用以下命令:

Math.ceil(num * 100)/100;
神乐小胖2020/03/09 17:19:13
米亚Eva2020/03/09 17:19:13

您应该使用:

Math.round( num * 100 + Number.EPSILON ) / 100

似乎没有人知道Number.EPSILON

同样值得注意的是,这并不是某些人所说JavaScript怪异之处

这就是浮点数在计算机中的工作方式。像99%的编程语言一样,JavaScript没有自制的浮点数。它依赖于CPU / FPU。计算机使用二进制,在二进制中,没有类似的任何数字0.1,而仅仅是二进制近似值。为什么?出于同样的原因,不能以十进制写1/3:其值为0.33333333 ...,且无穷三进制。

来吧Number.EPSILON该数字是1和双精度浮点数中存在下一个数字之间的差就是这样:1和1 + 之间没有数字Number.EPSILON

编辑:

正如评论中所要求的,让我们澄清一件事:加法Number.EPSILON仅在要取整的值是算术运算的结果时才相关,因为加法会吞噬一些浮点误差增量。

如果该值来自直接来源(例如:文字,用户输入或传感器),则没有用。

编辑(2019):

就像@maganap和一些人指出的那样,最好Number.EPSILON在相乘之前添加

Math.round( ( num + Number.EPSILON ) * 100 ) / 100

编辑(2019年12月):

最近,我使用类似于此函数的功能来比较可识别epsilon的数字:

const ESPILON_RATE = 1 + Number.EPSILON ;
const ESPILON_ZERO = Number.MIN_VALUE ;

function epsilonEquals( a , b ) {
  if ( Number.isNaN( a ) || Number.isNaN( b ) ) {
    return false ;
  }
  if ( a === 0 || b === 0 ) {
    return a <= b + EPSILON_ZERO && b <= a + EPSILON_ZERO ;
  }
  return a <= b * EPSILON_RATE && b <= a * EPSILON_RATE ;
}

我的用例是我多年开发的断言+数据验证库

实际上,在我使用的代码ESPILON_RATE = 1 + 4 * Number.EPSILONand中EPSILON_ZERO = 4 * Number.MIN_VALUE(是epsilon的四倍),因为我希望相等性检查器足够松散以累积浮点错误。

So far, it looks perfect for me. I hope it will help.

十三JimHarry2020/03/09 17:19:13

您可以使用

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}

我在MDN上发现了这一点他们的方法避免了提到的 1.005问题

roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
roundToTwo(1234.5678)
1234.57
江山如画2020/03/09 17:19:13

如果值是文本类型:

parseFloat("123.456").toFixed(2);

如果值为数字:

var numb = 123.23454;
numb = numb.toFixed(2);

不利的一面是,像1.5这样的值将给出“ 1.50”作为输出。@minitech建议的修复程序:

var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.

似乎Math.round是一个更好的解决方案。但这不是!在某些情况下,将全面正确:

Math.round(1.005 * 1000)/1000 // Returns 1 instead of expected 1.01!

toFixed() will also NOT round correctly in some cases (tested in Chrome v.55.0.2883.87)!

Examples:

parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.

1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.

I guess, this is because 1.555 is actually something like float 1.55499994 behind the scenes.

Solution 1 is to use a script with required rounding algorithm, for example:

function roundNumber(num, scale) {
  if(!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + scale)  + "e-" + scale);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if(+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  }
}

https://plnkr.co/edit/uau8BlS1cqbvWPCHJeOy?p=preview

NOTE: This is not a universal solution for everyone. There are several different rounding algorithms, your implementation can be different, depends on your requirements. https://en.wikipedia.org/wiki/Rounding

Solution 2 is to avoid front end calculations and pull rounded values from the backend server.

Stafan村村达蒙2020/03/09 17:19:12

采用 Math.round(num * 100) / 100

编辑:为了确保像1.005这样的东西正确取整,我们使用

Math.round((num + Number.EPSILON) * 100) / 100