Javascript 将数字截断为两位小数而不四舍五入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4187146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:17:55  来源:igfitidea点击:

Truncate number to two decimal places without rounding

javascript

提问by tempid

Suppose I have a value of 15.7784514, I want to display it 15.77 with no rounding.

假设我有一个 15.7784514 的值,我想将它显示为 15.77 而没有四舍五入。

var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));

Results in -

结果是 -

15.8
15.78
15.778
15.7784514000 

How do I display 15.77?

如何显示 15.77?

回答by Gumbo

Convert the number into a string, match the number up to the second decimal place:

将数字转换为字符串,将数字匹配到小数点后第二位:

function calc(theform) {
    var num = theform.original.value, rounded = theform.rounded
    var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
    rounded.value = with2Decimals
}
<form onsubmit="return calc(this)">
Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" />
<br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly>
</form>

The toFixedmethod fails in some cases unlike toString, so be very careful with it.

toFixed与 不同toString,该方法在某些情况下会失败,因此要非常小心。

回答by guya

Update 5 Nov 2016

2016 年 11 月 5 日更新

New answer, always accurate

新答案,始终准确

function toFixed(num, fixed) {
    var re = new RegExp('^-?\d+(?:\.\d{0,' + (fixed || -1) + '})?');
    return num.toString().match(re)[0];
}

As floating point math in javascriptwill always have edge cases, the previous solution will be accurate most of the time which is not good enough. There are some solutions to this like num.toPrecision, BigDecimal.js, and accounting.js. Yet, I believe that merely parsing the string will be the simplest and always accurate.

由于javascript 中的浮点数学总是有边缘情况,以前的解决方案在大多数情况下都是准确的,这还不够好。有这一些解决方案,如num.toPrecisionBigDecimal.jsaccounting.js。然而,我相信仅解析字符串将是最简单且始终准确的。

Basing the update on the well written regex from the accepted answer by @Gumbo, this new toFixed function will always work as expected.

根据@Gumbo 接受的答案中编写良好的正则表达式的更新,这个新的 toFixed 函数将始终按预期工作。



Old answer, not always accurate.

旧答案,并不总是准确的。

Roll your own toFixed function:

滚动你自己的 toFixed 函数:

function toFixed(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

回答by ベンノスケ

I opted to write this instead to manually remove the remainder with strings so I don't have to deal with the math issues that come with numbers:

我选择写这个来手动删除带有字符串的余数,这样我就不必处理数字带来的数学问题:

num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
Number(num); //If you need it back as a Number

This will give you "15.77" with num = 15.7784514;

这将为您提供 num = 15.7784514 的“15.77”;

回答by SC1000

October 2017

2017 年 10 月

General solution to truncate (no rounding) a number to the n-th decimal digit and convert it to a string with exactly n decimal digits, for any n≥0.

对于任何 n≥0,将数字截断(不四舍五入)为第 n 个十进制数字并将其转换为恰好具有 n 个十进制数字的字符串的通用解决方案。

function toFixedTrunc(x, n) {
  const v = (typeof x === 'string' ? x : x.toString()).split('.');
  if (n <= 0) return v[0];
  let f = v[1] || '';
  if (f.length > n) return `${v[0]}.${f.substr(0,n)}`;
  while (f.length < n) f += '0';
  return `${v[0]}.${f}`
}

where x can be either a number (which gets converted into a string) or a string.

其中 x 可以是数字(转换为字符串)或字符串。

Here are some tests for n=2 (including the one requested by OP):

以下是 n=2 的一些测试(包括 OP 要求的测试):

0           => 0.00
0.01        => 0.01
0.5839      => 0.58
0.999       => 0.99
1.01        => 1.01
2           => 2.00
2.551       => 2.55
2.99999     => 2.99
4.27        => 4.27
15.7784514  => 15.77
123.5999    => 123.59
0.000000199 => 1.99 *

* As mentioned in the note, that's due to javascript implicit conversion into exponential for "1.99e-7" And for some other values of n:

* 如注释中所述,这是由于 javascript 隐式转换为“1.99e-7”的指数以及其他一些 n 值:

15.001097   => 15.0010 (n=4)
0.000003298 => 0.0000032 (n=7)
0.000003298257899 => 0.000003298257 (n=12)

回答by Martin Varmus

parseInt is faster then Math.floor

parseInt 比 Math.floor 快

function floorFigure(figure, decimals){
    if (!decimals) decimals = 2;
    var d = Math.pow(10,decimals);
    return (parseInt(figure*d)/d).toFixed(decimals);
};

floorFigure(123.5999)    =>   "123.59"
floorFigure(123.5999, 3) =>   "123.599"

回答by Imran Pollob

Simple do this

简单做这个

number = parseInt(number * 100)/100;

回答by Alex Peng

num = 19.66752
f = num.toFixed(3).slice(0,-1)
alert(f)

This will return 19.66

这将返回 19.66

回答by jtrick

These solutions do work, but to me seem unnecessarily complicated. I personally like to use the modulus operator to obtain the remainder of a division operation, and remove that. Assuming that num = 15.7784514:

这些解决方案确实有效,但对我来说似乎不必要地复杂。我个人喜欢使用模运算符来获得除法运算的余数,然后将其删除。假设 num = 15.7784514:

num-=num%.01;

This is equivalent to saying num = num - (num % .01).

这相当于说 num = num - (num % .01)。

回答by David D

The answers here didn't help me, it kept rounding up or giving me the wrong decimal.

这里的答案对我没有帮助,它一直在四舍五入或给我错误的小数。

my solution converts your decimal to a string, extracts the characters and then returns the whole thing as a number.

我的解决方案将您的十进制转换为字符串,提取字符,然后将整个内容作为数字返回。

function Dec2(num) {
  num = String(num);
  if(num.indexOf('.') !== -1) {
    var numarr = num.split(".");
    if (numarr.length == 1) {
      return Number(num);
    }
    else {
      return Number(numarr[0]+"."+numarr[1].charAt(0)+numarr[1].charAt(1));
    }
  }
  else {
    return Number(num);
  }  
}

Dec2(99); // 99
Dec2(99.9999999); // 99.99
Dec2(99.35154); // 99.35
Dec2(99.8); // 99.8
Dec2(10265.985475); // 10265.98

回答by Alpha and Omega

My version for positive numbers:

我的正数版本:

function toFixed_norounding(n,p)
{
    var result = n.toFixed(p);
    return result <= n ? result: (result - Math.pow(0.1,p)).toFixed(p);
}

Fast, pretty, obvious. (version for positive numbers)

快速,漂亮,明显。(正数版本)