1

I suspect that this isn't possible, but giving it a try:

Is it possible to determine the number of decimal points of a number, whether or not those decimal points are trailing zeros?

getPrecision(3) // 0
getPrecision(3.2) // 1
getPrecision(2.30) // 2

I've found a couple of solutions for the first two cases (including this: How do I get the decimal places of a floating point number in Javascript?) but nothing for the last case. Converting 3.20 to a string results in "3.2", which doesn't help, and I'm about out of ideas.

ebbishop
  • 1,833
  • 2
  • 20
  • 45
  • Since you can't store 3.20 as an integer and maintain the last 0, you could feasibly always pass the value around as a string. Split the string on the '.' and doing string length on '2.30'.split('.')[1].length - again, assuming you always pass your numbers around as strings. – Brant Jan 03 '20 at 16:09
  • @Brant Unfortunately, I want to be able to handle values that are originally numbers. With strings I can do what you suggest, but in converting a number to a string, I lose the last `0`. – ebbishop Jan 03 '20 at 16:49
  • What data type is being used to store the numbers? A Javascript number is usually an IEEE 754 64-bit binary float, for which decimal places are meaningless. For example, the closest to 2.30 has value 2.29999999999999982236431605997495353221893310546875 – Patricia Shanahan Jan 03 '20 at 16:52
  • 3
    2.29999999999999982236431605997495353221893310546875 is also the closest to 2.3, 2.30000, 2.3000000000000, etc. They will all be represented identically unless you are using some special data type that preserves the number of decimal places in the original input. – Patricia Shanahan Jan 03 '20 at 17:39
  • Conceptually all finite `double` can be represented as decimal text with any amount of trailing zeros. `double q = 5; q/= 2;` `q` can be printed as 2.5, 2.50, 2.500, etc. – chux - Reinstate Monica Jan 04 '20 at 22:19

1 Answers1

0

Yes, this is possible but only with a trick

First of all, as per your problem statement, if you ask javascript to split and count your float value into 2 integers then it won't include trailing 0s of it.

Let's satisfy our requirement here with a trick ;)

In the below function you need to pass a value in string format and it will do your work

function getPrecision(value){
a = value.toString()
console.log('a ->',a)
b = a.split('.')
console.log('b->',b)
return b[1].length

getPrecision('12.12340') // Call a function

For an example, run the below logic

value = '12.12340'
a = value.toString()
b = a.split('.')
console.log('count of trailing decimals->',b[1].length)

That's it! Just pass your float value in string format and you are done! Thank you!

Omkar Hande
  • 71
  • 1
  • 4