Question Javascript Math.pow bug

Status
Not open for further replies.

salm2s

Honorable
Jul 21, 2017
266
6
10,815
Hi there,
I was experimenting with some js code with Math.pow and I found this weird issue.
Here is the code I was using:
Code:
function convertAmountFormat(amount, invert = false) {
    decimals = 8
    if (!invert) {
        return parseFloat((amount / Math.pow(10, decimals)).toFixed(decimals))
    }
    else {
        return parseInt(amount * Math.pow(10, decimals))
    }
}

And then I did:
convertAmountFormat(parseFloat(a) + convertAmountFormat(1000), true)

Where a is any positive integer

When a is, for example: 2, It returns:
Code:
convertAmountFormat(parseFloat(2) + convertAmountFormat(1000), true)
= 200001000

However, when a is either 4 or 5:
Code:
convertAmountFormat(parseFloat(4) + convertAmountFormat(1000), true)
= 400000999

convertAmountFormat(parseFloat(5) + convertAmountFormat(1000), true)
= 500000999

Is there a way I can fix this bug/issue?

Thanks,
salm2s
 
Last edited:

Ralston18

Titan
Moderator
So your exectation is that the results of amount (a) when a = 4 or 5 to be 4.00001000 and 5.00001000 respectively.

Is that correct?

Experiment a bit more: what happens if you change "decimals" to 7 or 9. Maybe even10?

What about that ".toFixed(decimals)"?

Why, in your If, Then, Else logic are the "return" code lines different?
 

salm2s

Honorable
Jul 21, 2017
266
6
10,815
So your exectation is that the results of amount (a) when a = 4 or 5 to be 4.00001000 and 5.00001000 respectively.

Is that correct?

Experiment a bit more: what happens if you change "decimals" to 7 or 9. Maybe even10?

What about that ".toFixed(decimals)"?

Why, in your If, Then, Else logic are the "return" code lines different?

I think I found a solution:
Code:
convertAmountFormat(parseFloat(a), true) + convertAmountFormat(1000)

When using this:
Code:
convertAmountFormat(parseFloat(4), true) + convertAmountFormat(1000)
= 4.00001000

Thanks for your help
 
Status
Not open for further replies.