简体   繁体   English

在JavaScript中计算小数点后的数字

[英]Counting numbers after decimal point in JavaScript

I have a problem in JavaScript. 我在JavaScript中有问题。 Is it possible to check how many numbers are after the decimal point? 是否可以检查小数点后有多少个数字? I tried to do it using a.toString().split(".")[1] ), but if there is no decimal point in the number, there is an error. 我尝试使用a.toString().split(".")[1] )执行此操作,但是如果数字中没有小数点,则会出现错误。 What should I do if I want the system to do nothing if there is no decimal point? 如果我希望系统在没有小数点的情况下不执行任何操作,该怎么办?

You're on the right track. 您走在正确的轨道上。 You can also .includes('.') to test if it contains a decimal along with .length to return the length of the decimal portion. 您还可以使用.includes('.')来测试它是否包含小数,并使用.length返回小数部分的长度。

 function decimalCount (number) { // Convert to String const numberAsString = number.toString(); // String Contains Decimal if (numberAsString.includes('.')) { return numberAsString.split('.')[1].length; } // String Does Not Contain Decimal return 0; } console.log(decimalCount(1.123456789)) // 9 console.log(decimalCount(123456789)) // 0 

Convert to a string, split on “.”, then when there is no “.” to split on, assume it's empty string '' (the part you're missing), then get said string's length: 转换为字符串,在“。”上分割,然后在没有“。”分割时,假定它是空字符串'' (您缺少的部分),然后得到该字符串的长度:

 function numDigitsAfterDecimal(x) { var afterDecimalStr = x.toString().split('.')[1] || '' return afterDecimalStr.length } console.log(numDigitsAfterDecimal(1.23456)) console.log(numDigitsAfterDecimal(0)) 

You could check if no dot is available, then return zero, otherwise return the delta of the lenght and index with an adjustment. 您可以检查是否没有可用的点,然后返回零,否则返回经过调整的长度和索引的差值。

 function getDigits(v) { var s = v.toString(), i = s.indexOf('.') + 1; return i && s.length - i; } console.log(getDigits(0)); console.log(getDigits(0.002)); console.log(getDigits(7.654321)); console.log(getDigits(1234567890.654321)); 

The condition you need is: 您需要的条件是:

number.split('.')[1].length

It checks if there are any numbers after the dot which separates the number from its decimal part. 它检查在点后是否有任何数字将数字与其小数部分分开。

I'm not sure if you are able to use split on numbers though. 我不确定您是否能够使用数字split If not, parse it to a string. 如果不是,则将其解析为字符串。

You first need to convert the decimal number to string and then get the count of character after decimal point, 您首先需要将十进制数字转换为字符串,然后获取小数点后的字符数,

var a = 10.4578;
var str = a.toString();
if(str){
   var val = str.split('.');
   if(val && val.length == 2){
     alert('Length of number after decimal point is ', val[1].length);
   } else {
    alert('Not a decimal number');
   }
}

The output is 4 输出为4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM