我是否错过了一个标准API调用,该调用从一个数字中移除尾随的不重要的零?
var x = 1.234000; // to become 1.234
var y = 1.234001; // stays 1.234001
Number.toFixed()和Number.toPrecision()不是我想要的。
我是否错过了一个标准API调用,该调用从一个数字中移除尾随的不重要的零?
var x = 1.234000; // to become 1.234
var y = 1.234001; // stays 1.234001
Number.toFixed()和Number.toPrecision()不是我想要的。
当前回答
如果由于任何原因(比如涉及到金钱浮动)不能使用float,并且已经从表示正确数字的字符串开始,您可以发现这个解决方案很方便。它将表示数字的字符串转换为表示数字的字符串,后面不带零。
function removeTrailingZeroes( strAmount ) {
// remove all trailing zeroes in the decimal part
var strDecSepCd = '.'; // decimal separator
var iDSPosition = strAmount.indexOf( strDecSepCd ); // decimal separator positions
if ( iDSPosition !== -1 ) {
var strDecPart = strAmount.substr( iDSPosition ); // including the decimal separator
var i = strDecPart.length - 1;
for ( ; i >= 0 ; i-- ) {
if ( strDecPart.charAt(i) !== '0') {
break;
}
}
if ( i=== 0 ) {
return strAmount.substring(0, iDSPosition);
} else {
// return INTPART and DS + DECPART including the rightmost significant number
return strAmount.substring(0, iDSPosition) + strDecPart.substring(0,i + 1);
}
}
return strAmount;
}
其他回答
我首先使用了matti-lyra和gary的答案的组合:
r=(+n).toFixed(4).replace(/\.0+$/,'')
结果:
1234870.98762341:“1234870.9876” 1230009100:“1230009100” 0.0012234:“0.0012” 0.1200234:“0.12” 0.000001231:“0” 0.10001:“0.1000” "asdf": "NaN"(所以没有运行时错误)
有点问题的情况是0.10001。我最终使用了这个更长的版本:
r = (+n).toFixed(4);
if (r.match(/\./)) {
r = r.replace(/\.?0+$/, '');
}
1234870.98762341:“1234870.9876” 1230009100:“1230009100” 0.0012234:“0.0012” 0.1200234:“0.12” 0.000001231:“0” 0.10001:“0.1” "asdf": "NaN"(所以没有运行时错误)
更新:这是加里的新版本(见评论):
r=(+n).toFixed(4).replace(/([0-9]+(\.[0-9]+[1-9])?)(\.?0+$)/,'$1')
这将得到与上面相同的结果。
像这样乘以1怎么样?
var x = 1.234000*1; // becomes 1.234
var y = 1.234001*1; // stays as 1.234001
如果我们有一个数字的s字符串表示形式,例如我们可以使用number的.toFixed(digits)方法(或任何其他方法)来获得,那么为了从s字符串中删除不重要的末尾零,我们可以使用:
s.replace(/(\.0*|(?<=(\..*))0*)$/, '')
/**********************************
* Results for various values of s:
**********************************
*
* "0" => 0
* "0.000" => 0
*
* "10" => 10
* "100" => 100
*
* "0.100" => 0.1
* "0.010" => 0.01
*
* "1.101" => 1.101
* "1.100" => 1.1
* "1.100010" => 1.10001
*
* "100.11" => 100.11
* "100.10" => 100.1
*/
replace()中使用的正则表达式解释如下:
In the first place please pay the attention to the | operator inside the regular expression, which stands for "OR", so, the replace() method will remove from s two possible kinds of substring, matched either by the (\.0*)$ part OR by the ((?<=(\..*))0*)$ part. The (\.0*)$ part of regex matches a dot symbol followed by all the zeros and nothing else till to the end of the s. This might be for example 0.0 (.0 is matched & removed), 1.0 (.0 is matched & removed), 0.000 (.000 is matched & removed) or any similar string with all the zeros after the dot, so, all the trailing zeros and the dot itself will be removed if this part of regex will match. The ((?<=(\..*))0*)$ part matches only the trailing zeros (which are located after a dot symbol followed by any number of any symbol before start of the consecutive trailing zeros). This might be for example 0.100 (trailing 00 is matched & removed), 0.010 (last 0 is matched & removed, note that 0.01 part do NOT get matched at all thanks to the "Positive Lookbehind Assertion", i.e. (?<=(\..*)), which is in front of 0* in this part of regex), 1.100010 (last 0 is matched & removed), etc. If neither of the two parts of expression will match, nothing gets removed. This might be for example 100 or 100.11, etc. So, if an input does not have any trailing zeros then it stays unchanged.
更多使用.toFixed(数字)的例子(在下面的例子中使用了字面值“1000.1010”,但我们可以假设变量):
let digits = 0; // Get `digits` from somewhere, for example: user input, some sort of config, etc.
(+"1000.1010").toFixed(digits).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000'
(+"1000.1010").toFixed(digits = 1).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.1'
(+"1000.1010").toFixed(digits = 2).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.1'
(+"1000.1010").toFixed(digits = 3).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.101'
(+"1000.1010").toFixed(digits = 4).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.101'
(+"1000.1010").toFixed(digits = 5).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.101'
(+"1000.1010").toFixed(digits = 10).replace(/(\.0*|(?<=(\..*))0*)$/, '');
// Result: '1000.101'
要使用replace()中使用的上述正则表达式,我们可以访问:https://regex101.com/r/owj9fz/1
如果你使用toFixed(n)其中n > 0,一个更简单和稳定(没有更多的浮点运算)的解决方案可以是:
(+n).toFixed(2).replace(/(\.0+|0+)$/, '')
// 0 => 0
// 0.1234 => 0.12
// 0.1001 => 0.1
// 1 => 1
// 1.1234 => 1.12
// 1.1001 => 1.1
// 100 => 100
// 100.1234 => 100.12
// 100.1001 => 100.1
PS:如果你使用toFixed(0),那么不需要更换。
我有一个类似的实例,我想在必要的地方使用. tofixed(),但我不想在它不是时使用填充。所以我最终将parseFloat与toFixed结合使用。
固定无填充
parseFloat(n.toFixed(4));
另一个选项几乎做同样的事情 这个答案可能会帮助你做决定
Number(n.toFixed(4));
toFixed将数字四舍五入/填充为特定的长度,但也将其转换为字符串。将其转换回数字类型不仅可以使数字在算术上更安全地使用,还可以自动删除后面的任何0。例如:
var n = "1.234000";
n = parseFloat(n);
// n is 1.234 and in number form
因为即使你定义了一个后面带0的数字,它们也会被省略。
var n = 1.23000;
// n == 1.23;