0

I have an issue trying to round some numbers to two digits.

I know it's not that complicated, I'm trying to do it this way:

console.log(parseFloat(3.4155113501943415e-303).toFixed(2))
console.log(parseFloat(8.224160000472033e-304).toFixed(2))
console.log(parseFloat(8.769850182148146e-304).toFixed(2))

But I have an issue with toFixed, it only returns 0.00 for all my numbers. I suspect that it's due to that fact that my numbers are written this way:

3.4155113501943415e-303
8.224160000472033e-304
8.769850182148146e-304

​etc.

With the e-304 at the end. Is it the issue? Do I have to delete that part or is there any way around it?

Igor
  • 60,821
  • 10
  • 100
  • 175
Guillaume Marc
  • 67
  • 1
  • 10
  • 3
    No, that's not the issue, both parseFloat and toFixed work perfectly fine here. The numbers are just tiny, `e-303` means `*10^(-303)`, so 303 zeros before the first digit of that number comes – Luca Kiebel Sep 12 '18 at 14:59
  • 1
    What value(s) were you expecting (and why)? – Igor Sep 12 '18 at 15:02
  • Oh you're right I'm stupid I totally forgot about that. It is supposed to be NASDAQ and CAC40 stock, that's why I didn't expect such small numbers, and in the exemple they gave me, the numbers are much higher, I'll figure it out I guess – Guillaume Marc Sep 12 '18 at 15:03
  • Does the API that you're dealing with propose any libraries that can handle big/small decimal numbers for you? Doing money calculation with `float`s is like asking for *Office Space* to happen. – zero298 Sep 12 '18 at 15:08
  • Personally I prefer the library [decimal.js](https://www.npmjs.com/package/decimal.js/v/3.0.0) when working with partial numbers in javascript. – Igor Sep 12 '18 at 15:10

2 Answers2

0

I think I saw a problem same as yours Parsing and converting exponential values to decimal in JavaScript. The problem is that 3.4155113501943415e-303 means three hundred zeros in front 0.0000..(and so on up to 300)..00000034155113501943415. So when you use toFixed(2) you get only 0.00. On the link I gave you there is a function which turns exponential number to double and then you can round it.

stanimirsp
  • 2,548
  • 2
  • 26
  • 36
0

I just used toPrecision() and it worked. In the example they gave me they just removed the "e-n" which is just lazy in my opinion, we just don't know if it's e-343 or e-342 for example, which is a crazy thing to do.

Anyway, I've found the answer, thank you all!

Guillaume Marc
  • 67
  • 1
  • 10