Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to retrieve the number of decimals of a *string* number?

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.

In other words, the retr_dec() method should return the following:

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

like image 536
Jérôme Verstrynge Avatar asked May 04 '12 18:05

Jérôme Verstrynge


People also ask

How do you find the decimal of a string?

You can check like below, String decimalPoint = '1.23'; Boolean isValidDecimal = true; if(decimalPoint != null){ try{ Decimal. valueOf(decimalPoint); } catch(TypeException e){ isValidDecimal = false; } } system.

How do you extract the decimal part of a number?

An alternative approach is to use the modulo operator. Use the modulo (%) operator to get the decimal part of a number, e.g. const decimal = num % 1 . When used with a divisor of 1 , the modulo operator returns the decimal part of the number.

How do you return a decimal in JavaScript?

floor( ). Math. abs( ): The Math. abs() function in JavaScript is used to return the absolute value of a number.

How do you extract the decimal part of a number in Java?

To get the decimal part you could do this: double original = 1.432d; double decimal = original % 1d; Note that due to the way that decimals are actually thought of, this might kill any precision you were after.


1 Answers

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 
like image 64
Mike Samuel Avatar answered Sep 23 '22 02:09

Mike Samuel