Javascript:如何检索*字符串*数字的小数位数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10454518/
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
Javascript: How to retrieve the number of decimals of a *string* number?
提问by Jér?me Verstrynge
I have a set of string numbers having decimals, for example: 23.456
, 9.450
, 123.01
... I need to retrieve the number of decimals for each number, knowing that they have at least 1 decimal.
我有一组带小数的字符串数字,例如:23.456
, 9.450
, 123.01
... 我需要检索每个数字的小数位数,知道它们至少有 1 个小数。
In other words, the retr_dec()
method should return the following:
换句话说,该retr_dec()
方法应返回以下内容:
retr_dec("23.456") -> 3
retr_dec("9.450") -> 3
retr_dec("123.01") -> 2
Trailing zeros do count as a decimal in this case, unlike in this related question.
在这种情况下,尾随零确实算作小数,与此相关问题不同。
Is there an easy/delivered method to achieve this in Javascript or should I compute the decimal point position and compute the difference with the string length? Thanks
是否有一种简单/交付的方法可以在 Javascript 中实现这一点,还是应该计算小数点位置并计算与字符串长度的差异?谢谢
回答by Mike Samuel
function decimalPlaces(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
The extra complexity is to handle scientific notation so
额外的复杂性是处理科学记数法,所以
decimalPlaces('.05') 2 decimalPlaces('.5') 1 decimalPlaces('1') 0 decimalPlaces('25e-100') 100 decimalPlaces('2.5e-99') 100 decimalPlaces('.5e1') 0 decimalPlaces('.25e1') 1
decimalPlaces('.05') 2 decimalPlaces('.5') 1 decimalPlaces('1') 0 decimalPlaces('25e-100') 100 decimalPlaces('2.5e-99') 100 decimalPlaces('.5e1') 0 decimalPlaces('.25e1') 1
回答by Hyman
function retr_dec(num) {
return (num.split('.')[1] || []).length;
}
回答by Daniel Bidulock
function retr_dec(numStr) {
var pieces = numStr.split(".");
return pieces[1].length;
}
回答by Phrogz
Since there is not already a regex-based answer:
由于还没有基于正则表达式的答案:
/\d*$/.exec(strNum)[0].length
Note that this "fails" for integers, but per the problem specification they will never occur.
请注意,这对于整数“失败”,但根据问题规范,它们永远不会发生。
回答by Kamlesh Kumar
You could get the length of the decimal part of your number this way:
您可以通过这种方式获得数字小数部分的长度:
var value = 192.123123;
stringValue = value.toString();
length = stringValue.split('.')[1].length;
It makes the number a string, splits the string in two (at the decimal point) and returns the length of the second element of the array returned by the split operation and stores it in the 'length' variable.
它使数字成为字符串,将字符串一分为二(在小数点处),并返回由拆分操作返回的数组的第二个元素的长度,并将其存储在 'length' 变量中。
回答by guest271314
Try using String.prototype.match()
with RegExp
/\..*/
, return .length
of matched string -1
尝试使用String.prototype.match()
with RegExp
/\..*/
,返回.length
匹配的字符串-1
function retr_decs(args) {
return /\./.test(args) && args.match(/\..*/)[0].length - 1 || "no decimal found"
}
console.log(
retr_decs("23.456") // 3
, retr_decs("9.450") // 3
, retr_decs("123.01") // 2
, retr_decs("123") // "no decimal found"
)
回答by Gabriel Nahmias
A slight modification of the currently accepted answer, this adds to the Number
prototype, thereby allowing all number variables to execute this method:
对当前接受的答案稍作修改,这增加了Number
原型,从而允许所有数字变量执行此方法:
if (!Number.prototype.getDecimals) {
Number.prototype.getDecimals = function() {
var num = this,
match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match)
return 0;
return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
}
}
It can be used like so:
它可以像这样使用:
// Get a number's decimals.
var number = 1.235256;
console.debug(number + " has " + number.getDecimals() + " decimal places.");
// Get a number string's decimals.
var number = "634.2384023";
console.debug(number + " has " + parseFloat(number).getDecimals() + " decimal places.");
Utilizing our existing code, the second case could also be easily added to the String
prototype like so:
利用我们现有的代码,第二种情况也可以很容易地添加到String
原型中,如下所示:
if (!String.prototype.getDecimals) {
String.prototype.getDecimals = function() {
return parseFloat(this).getDecimals();
}
}
Use this like:
像这样使用:
console.debug("45.2342".getDecimals());
回答by Liam Middleton
A bit of a hybrid of two others on here but this worked for me. Outside cases in my code weren't handled by others here. However, I had removed the scientific decimal place counter. Which I would have loved at uni!
这里有点像另外两个人的混合体,但这对我有用。我的代码中的外部案例没有由这里的其他人处理。但是,我已经删除了科学小数位计数器。我在大学时会喜欢的!
numberOfDecimalPlaces: function (number) {
var match = ('' + number).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match || match[0] == 0) {
return 0;
}
return match[0].length;
}
回答by Orden
I had to deal with very small numbers so I created a version that can handle numbers like 1e-7.
我不得不处理非常小的数字,所以我创建了一个可以处理像 1e-7 这样的数字的版本。
Number.prototype.getPrecision = function() {
var v = this.valueOf();
if (Math.floor(v) === v) return 0;
var str = this.toString();
var ep = str.split("e-");
if (ep.length > 1) {
var np = Number(ep[0]);
return np.getPrecision() + Number(ep[1]);
}
var dp = str.split(".");
if (dp.length > 1) {
return dp[1].length;
}
return 0;
}
document.write("NaN => " + Number("NaN").getPrecision() + "<br>");
document.write("void => " + Number("").getPrecision() + "<br>");
document.write("12.1234 => " + Number("12.1234").getPrecision() + "<br>");
document.write("1212 => " + Number("1212").getPrecision() + "<br>");
document.write("0.0000001 => " + Number("0.0000001").getPrecision() + "<br>");
document.write("1.12e-23 => " + Number("1.12e-23").getPrecision() + "<br>");
document.write("1.12e8 => " + Number("1.12e8").getPrecision() + "<br>");
回答by dke
function decimalPlaces(n) {
if (n === NaN || n === Infinity)
return 0;
n = ('' + n).split('.');
if (n.length == 1) {
if (Boolean(n[0].match(/e/g)))
return ~~(n[0].split('e-'))[1];
return 0;
}
n = n[1].split('e-');
return n[0].length + ~~n[1];
}