从数字中删除不重要的尾随零?

时间:2022-05-10 22:18:31

Have I missed a standard API call that removes trailing insignificant zeros from a number?

我是否错过了一个标准的API调用,它从一个数字中删除了不重要的0 ?

Ex.

前女友。

var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001

Number.toFixed() and Number.toPrecision() are not quite what I'm looking for.

Number.toFixed()和Number.toPrecision()并不是我想要的。

9 个解决方案

#1


88  

If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.

如果您将它转换为一个字符串,它将不会显示任何尾随的0,因为它是作为数字而不是字符串创建的,所以不会首先存储在变量中。

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

#2


133  

I had a similar instance where I wanted to use .toFixed() where necessary, but I didn't want the padding when it wasn't. So I ended up using parseFloat in conjunction with toFixed.

我有一个类似的实例,我想在需要的时候使用. tofixed(),但是我不想在不需要的时候使用填充。最后我使用了parseFloat和toFixed。

toFixed without padding

toFixed没有填充

parseFloat(n.toFixed(4));

Another option that does almost the same thing
This answer may help your decision

另一种几乎同样的方法可以帮助你做出决定。

Number(n.toFixed(4));

toFixed will truncate/pad the number to a specific length, but also convert it to a string. Converting that back to a numeric type will not only make the number safer to use arithmetically, but also automatically drop any trailing 0's. For example:

toFixed将把数字截断到一个特定的长度,但也将它转换成一个字符串。将其转换为数字类型不仅可以使数字更安全,还可以自动删除任何后面的0。例如:

var n = "1.234000";
    n = parseFloat(n);
 // n is 1.234 and in number form

Because even if you define a number with trailing zeros they're dropped.

因为即使你用尾随零来定义一个数字,它们也会被删除。

var n = 1.23000;
 // n == 1.23;

#3


15  

I first used a combination of matti-lyra and gary's answers:

我首先把matti-lyra和gary的回答结合起来:

r=(+n).toFixed(4).replace(/\.0+$/,'')

Results:

结果:

  • 1234870.98762341: "1234870.9876"
  • 1234870.98762341:“1234870.9876”
  • 1230009100: "1230009100"
  • 1230009100:“1230009100”
  • 0.0012234: "0.0012"
  • 0.0012234:“0.0012”
  • 0.1200234: "0.12"
  • 0.1200234:“0.12”
  • 0.000001231: "0"
  • 0.000001231:“0”
  • 0.10001: "0.1000"
  • 0.10001:“0.1000”
  • "asdf": "NaN" (so no runtime error)
  • “asdf”:“NaN”(因此没有运行时错误)

The somewhat problematic case is 0.10001. I ended up using this longer version:

有点问题的情况是0。10001。我最终使用了这个较长的版本:

    r = (+n).toFixed(4);
    if (r.match(/\./)) {
      r = r.replace(/\.?0+$/, '');
    }
  • 1234870.98762341: "1234870.9876"
  • 1234870.98762341:“1234870.9876”
  • 1230009100: "1230009100"
  • 1230009100:“1230009100”
  • 0.0012234: "0.0012"
  • 0.0012234:“0.0012”
  • 0.1200234: "0.12"
  • 0.1200234:“0.12”
  • 0.000001231: "0"
  • 0.000001231:“0”
  • 0.10001: "0.1"
  • 0.10001:“0.1”
  • "asdf": "NaN" (so no runtime error)
  • “asdf”:“NaN”(因此没有运行时错误)

Update: And this is Gary's newer version (see comments):

更新:这是Gary的更新版本(见评论):

r=(+n).toFixed(4).replace(/([0-9]+(\.[0-9]+[1-9])?)(\.?0+$)/,'$1')

This gives the same results as above.

这与上面的结果相同。

#4


8  

The toFixed method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.

如果需要,toFixed方法将执行适当的舍入。它还将添加尾随零,这并不总是理想的。

(4.55555).toFixed(2);
//-> "4.56"

(4).toFixed(2);
//-> "4.00"

If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.

如果您将返回值转换为一个数字,那么后面的0将被删除。这是一种比自己做舍入或截断计算更简单的方法。

+(4.55555).toFixed(2);
//-> 4.56

+(4).toFixed(2);
//-> 4

#5


2  

I had the basically the same requirement, and found that there is no built-in mechanism for this functionality.

我有基本相同的需求,并且发现这个功能没有内置的机制。

In addition to trimming the trailing zeros, I also has the need to round off and optionally format the output for the user's current locale (i.e. 123,456.789).

除了去掉末尾的0之外,我还需要对用户当前语言环境(即123,456.789)的输出进行四舍五入和可选的格式化。

All of my work on this has been included as prettyFloat.js (MIT Licensed) on GitHub: https://github.com/dperish/prettyFloat.js

我在这方面的所有工作都包含在prettyFloat中。js (MIT许可)在GitHub上:https://github.com/dperish/prettyFloat.js


Usage Examples:

使用例子:

prettyFloat(1.111001, 3) // "1.111"
prettyFloat(1.111001, 4) // "1.111"
prettyFloat(1.1111001, 5) // "1.1111"
prettyFloat(1234.5678, 2) // "1234.57"
prettyFloat(1234.5678, 2, true) // "1,234.57" (en-us)

#6


2  

None of these solutions worked for me for very small numbers. http://numeraljs.com/ solved this for me.

对于很小的数字,这些解决方案对我都不起作用。http://numeraljs.com/为我解决了这个问题。

parseFloat(0.00000001.toFixed(8));
// 1e-8

numeral(0.00000001).format('0[.][00000000]');
// "0.00000001"

#7


2  

I needed to solve this problem too when Django was displaying Decimal type values in a text field. E.g. when '1' was the value. It would show '1.00000000'. If '1.23' was the value, it would show '1.23000000' (In the case of a 'decimal_places' setting of 8)

当Django在文本字段中显示十进制类型值时,我也需要解决这个问题。例如:when '1 is the value。它会显示“1.00000000”。如果“1.23”是值,它将显示“1.23000000”(在“decimal_places”设置为8的情况下)

Using parseFloat was not an option for me since it is possible it does not return the exact same value. toFixed was not an option since I did not want to round anything, so I created a function:

使用parseFloat对我来说不是一个选项,因为它可能不会返回相同的值。toFixed不是一个选项,因为我不想把任何东西都弄圆,所以我创建了一个函数:

function removeTrailingZeros(value) {
    value = value.toString();

    # if not containing a dot, we do not need to do anything
    if (value.indexOf('.') === -1) {
        return value;
    }

    # as long as the last character is a 0 or a dot, remove it
    while((value.slice(-1) === '0' || value.slice(-1) === '.') && value.indexOf('.') !== -1) {
        value = value.substr(0, value.length - 1);
    }
    return value;
}

#8


1  

Here's a possible solution:

这里有一个可能的解决方案:

var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001

eval(x) --> 1.234
eval(y) --> 1.234001

#9


0  

How about just multiplying by one like this?

像这样乘以一个呢?

var x = 1.234000*1; // becomes 1.234

var y = 1.234001*1; // stays as 1.234001

#1


88  

If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.

如果您将它转换为一个字符串,它将不会显示任何尾随的0,因为它是作为数字而不是字符串创建的,所以不会首先存储在变量中。

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

#2


133  

I had a similar instance where I wanted to use .toFixed() where necessary, but I didn't want the padding when it wasn't. So I ended up using parseFloat in conjunction with toFixed.

我有一个类似的实例,我想在需要的时候使用. tofixed(),但是我不想在不需要的时候使用填充。最后我使用了parseFloat和toFixed。

toFixed without padding

toFixed没有填充

parseFloat(n.toFixed(4));

Another option that does almost the same thing
This answer may help your decision

另一种几乎同样的方法可以帮助你做出决定。

Number(n.toFixed(4));

toFixed will truncate/pad the number to a specific length, but also convert it to a string. Converting that back to a numeric type will not only make the number safer to use arithmetically, but also automatically drop any trailing 0's. For example:

toFixed将把数字截断到一个特定的长度,但也将它转换成一个字符串。将其转换为数字类型不仅可以使数字更安全,还可以自动删除任何后面的0。例如:

var n = "1.234000";
    n = parseFloat(n);
 // n is 1.234 and in number form

Because even if you define a number with trailing zeros they're dropped.

因为即使你用尾随零来定义一个数字,它们也会被删除。

var n = 1.23000;
 // n == 1.23;

#3


15  

I first used a combination of matti-lyra and gary's answers:

我首先把matti-lyra和gary的回答结合起来:

r=(+n).toFixed(4).replace(/\.0+$/,'')

Results:

结果:

  • 1234870.98762341: "1234870.9876"
  • 1234870.98762341:“1234870.9876”
  • 1230009100: "1230009100"
  • 1230009100:“1230009100”
  • 0.0012234: "0.0012"
  • 0.0012234:“0.0012”
  • 0.1200234: "0.12"
  • 0.1200234:“0.12”
  • 0.000001231: "0"
  • 0.000001231:“0”
  • 0.10001: "0.1000"
  • 0.10001:“0.1000”
  • "asdf": "NaN" (so no runtime error)
  • “asdf”:“NaN”(因此没有运行时错误)

The somewhat problematic case is 0.10001. I ended up using this longer version:

有点问题的情况是0。10001。我最终使用了这个较长的版本:

    r = (+n).toFixed(4);
    if (r.match(/\./)) {
      r = r.replace(/\.?0+$/, '');
    }
  • 1234870.98762341: "1234870.9876"
  • 1234870.98762341:“1234870.9876”
  • 1230009100: "1230009100"
  • 1230009100:“1230009100”
  • 0.0012234: "0.0012"
  • 0.0012234:“0.0012”
  • 0.1200234: "0.12"
  • 0.1200234:“0.12”
  • 0.000001231: "0"
  • 0.000001231:“0”
  • 0.10001: "0.1"
  • 0.10001:“0.1”
  • "asdf": "NaN" (so no runtime error)
  • “asdf”:“NaN”(因此没有运行时错误)

Update: And this is Gary's newer version (see comments):

更新:这是Gary的更新版本(见评论):

r=(+n).toFixed(4).replace(/([0-9]+(\.[0-9]+[1-9])?)(\.?0+$)/,'$1')

This gives the same results as above.

这与上面的结果相同。

#4


8  

The toFixed method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.

如果需要,toFixed方法将执行适当的舍入。它还将添加尾随零,这并不总是理想的。

(4.55555).toFixed(2);
//-> "4.56"

(4).toFixed(2);
//-> "4.00"

If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.

如果您将返回值转换为一个数字,那么后面的0将被删除。这是一种比自己做舍入或截断计算更简单的方法。

+(4.55555).toFixed(2);
//-> 4.56

+(4).toFixed(2);
//-> 4

#5


2  

I had the basically the same requirement, and found that there is no built-in mechanism for this functionality.

我有基本相同的需求,并且发现这个功能没有内置的机制。

In addition to trimming the trailing zeros, I also has the need to round off and optionally format the output for the user's current locale (i.e. 123,456.789).

除了去掉末尾的0之外,我还需要对用户当前语言环境(即123,456.789)的输出进行四舍五入和可选的格式化。

All of my work on this has been included as prettyFloat.js (MIT Licensed) on GitHub: https://github.com/dperish/prettyFloat.js

我在这方面的所有工作都包含在prettyFloat中。js (MIT许可)在GitHub上:https://github.com/dperish/prettyFloat.js


Usage Examples:

使用例子:

prettyFloat(1.111001, 3) // "1.111"
prettyFloat(1.111001, 4) // "1.111"
prettyFloat(1.1111001, 5) // "1.1111"
prettyFloat(1234.5678, 2) // "1234.57"
prettyFloat(1234.5678, 2, true) // "1,234.57" (en-us)

#6


2  

None of these solutions worked for me for very small numbers. http://numeraljs.com/ solved this for me.

对于很小的数字,这些解决方案对我都不起作用。http://numeraljs.com/为我解决了这个问题。

parseFloat(0.00000001.toFixed(8));
// 1e-8

numeral(0.00000001).format('0[.][00000000]');
// "0.00000001"

#7


2  

I needed to solve this problem too when Django was displaying Decimal type values in a text field. E.g. when '1' was the value. It would show '1.00000000'. If '1.23' was the value, it would show '1.23000000' (In the case of a 'decimal_places' setting of 8)

当Django在文本字段中显示十进制类型值时,我也需要解决这个问题。例如:when '1 is the value。它会显示“1.00000000”。如果“1.23”是值,它将显示“1.23000000”(在“decimal_places”设置为8的情况下)

Using parseFloat was not an option for me since it is possible it does not return the exact same value. toFixed was not an option since I did not want to round anything, so I created a function:

使用parseFloat对我来说不是一个选项,因为它可能不会返回相同的值。toFixed不是一个选项,因为我不想把任何东西都弄圆,所以我创建了一个函数:

function removeTrailingZeros(value) {
    value = value.toString();

    # if not containing a dot, we do not need to do anything
    if (value.indexOf('.') === -1) {
        return value;
    }

    # as long as the last character is a 0 or a dot, remove it
    while((value.slice(-1) === '0' || value.slice(-1) === '.') && value.indexOf('.') !== -1) {
        value = value.substr(0, value.length - 1);
    }
    return value;
}

#8


1  

Here's a possible solution:

这里有一个可能的解决方案:

var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001

eval(x) --> 1.234
eval(y) --> 1.234001

#9


0  

How about just multiplying by one like this?

像这样乘以一个呢?

var x = 1.234000*1; // becomes 1.234

var y = 1.234001*1; // stays as 1.234001