Pregunta

I try to calculate a simple division in javascript but if my number is < 1000 The result is not good.

Here my code :

var cal = parseFloat(currentAmount.toString()) / parseFloat(currencyArray[i][j].toString())

if currencyArray[i][j] equal to 1,3703 and currentAmount = 100 my result is good (72.98) but if i put 1000 my result is not good (0.7298... )

¿Fue útil?

Solución

Due to the particular value you get, I'm going to guess that your currentAmount isn't 1000 as you claim, but rather 1,000 or 1 000 or even 1'000 in some countries. When parseFloat gets hold of that, it sees only 1 because , isn't a valid character in numbers. 1 / 1.3703 is 0.7298....

Numbers must not have thousand separators, and decimals must be a point. (As someone who grew up in France, I know this can be confusing!)

Otros consejos

OK, going for a wild guess.

It looks like you're dealing with numbers as strings, with bad formatting and you have "1 000" or "1,000" and you want it to be parsed as 1000. Your problem is that

parseFloat("1 000")

gives

1

In that case, strip the spaces :

var currentAmountAsNumber = parseFloat(currentAmount.toString().replace(/[ ,]/g,''))

But having a test case would probably let us simplify that.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top