0

I am trying to find the value of the 4th decimal place and check if it is a zero or not. If not I was planning on throwing an error message. For example 2.3189. I need to be able to check the value of the 4th decimal which in this case is 9. This is the code I have thus far. It seemed to be working for majority of cases but for example 1.2570. When I do the check for this number it says that the 0 is not a 0. When I do the same check with 1.2580 it says that the 0 is a 0. Any help with this would be greatly appreciated.

!!(submission && (quantity * 10000 % 10) === 0);
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Ryan
  • 103
  • 2
  • 8
  • 2
    Numbers in JavaScript are *binary* floating-point values. That is, they're stored as a mantissa and an exponent, with the exponent being a power of **2**, not 10. Thus, you cannot reliably perform operations like what you describe, because base-2 fractions and base-10 fractions are different. – Pointy Sep 20 '21 at 14:12
  • 2
    You can make the check more reliably by converting the number into a string and then finding whether the 4th character after the decimal point is `'0'`. – Timo Sep 20 '21 at 14:14
  • 1
    @Timo that is true, though depending on where the numbers come from there might still be surprising results (well, surprising to those who don't get how numbers work). – Pointy Sep 20 '21 at 14:18

2 Answers2

0

I'd do regex checking 4th place after '.' to be zero

var number = 0.554156;
/\.[0-9]{3}0/.test(number.toString())
digitalniweb
  • 838
  • 1
  • 7
  • 15
  • 1. A string converted to a string is still a string. The `.toString()` doesn't make much sense here. 2. This regex only matches digits if they do exist, `0.123` will not work even though it logically has a zero as a fourth digit after the dot. – VLAZ Sep 20 '21 at 14:16
  • Well of course it was supposed to be the number value... But I fixed it... – digitalniweb Sep 20 '21 at 14:19
0

You could make use of javascript expression for accessing the 4th decimal place since modulus operator has precision issues.

const quantity = 1.2570;
console.log(Number(quantity.toFixed(4).split('.')[1][3]));
Nitheesh
  • 19,238
  • 3
  • 22
  • 49