我是否错过了一个标准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;
}
其他回答
我写这个正则表达式是为了从包含数字的字符串的开头和结尾删除无关紧要的0、小数和空格:
const rxInsignificant = /^[\s0]+|(?<=\..*)[\s0.]+$|\.0+$|\.$/gm; 设 ary = [ "001.230", "2.", "3.00", "1000", " 0000000000000010000.10000000000000000000000 "]; ary.forEach((str)=> { console.log('“${str}” 变为 “${str.replace(rxInsignificant ,'')}”'); });
不幸的是,Safari仍然不支持2018年的规范,该规范为我们提供了正则表达式的回溯。自07-28-2017以来,此问题一直有一个开放的错误报告。
好消息是,在Firefox和所有Chromium衍生产品中,向后查找功能确实有效。希望Safari能收到更多的要求,并尽快实现这个标准。
与此同时,我写了这个函数来完成同样的任务,而不需要回顾:
function createRemoveInsignificantFunction() { const rxLeadingZeros = /^[\s0]+/; const rxEndingZeros = /[\s0]+$/; function removeInsignificant(str) { str = str.replace(rxLeadingZeros,''); let ary = str.split('.'); if (ary.length > 1) { ary[1] = ary[1].replace(rxEndingZeros,''); if (ary[1].length === 0) { return ary[0]; } else { return ary[0] + '.' + ary[1]; } } return str; } return removeInsignificant; } let removeInsignificant = createRemoveInsignificantFunction(); let ary = [ "001.230", "2.", "3.00", "1000", " 0000000000000010000.10000000000000000000000 "]; ary.forEach((str)=> { console.log(`"${str}" becomes "${removeInsignificant(str)}"`); });
当我有更多的时间时,我想弄清楚如何用一个正则表达式来完成这个任务,而不需要在其中查找。欢迎你在下面的评论中打败我。
我有基本相同的需求,但发现没有内置机制来实现此功能。
除了去掉后面的0之外,我还需要为用户的当前语言环境(即123,456.789)对输出进行四舍五入和格式化。
我在这方面的所有工作都包括在GitHub: https://github.com/dperish/prettyFloat.js上的prettyFloat.js (MIT许可)
使用例子:
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)
更新- 2018年8月
所有现代浏览器现在都支持ECMAScript国际化API,它提供了语言敏感的字符串比较、数字格式化以及日期和时间格式化。
const formatters = {
default: new Intl.NumberFormat(),
currency: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
whole: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
oneDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 1, maximumFractionDigits: 1 }),
twoDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 })
};
formatters.twoDecimal.format(1234.5678); // result: "1,234.57"
formatters.currency.format(28761232.291); // result: "$28,761,232"
对于旧的浏览器,您可以使用这个填充:https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en
对于非常小的数,这些解都不适用。http://numeraljs.com/为我解决了这个问题。
parseFloat(0.00000001.toFixed(8));
// 1e-8
numeral(0.00000001).format('0[.][00000000]');
// "0.00000001"
这里有一个可能的解决方案:
var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001
eval(x) --> 1.234
eval(y) --> 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