Convert Dollars to Cents in Javascript

Convert Dollars to Cents in Javascript

I am trying to convert $3.77 (USD) to cents as follows:

const number = "3.77"
const separe = number.replace(".", "")

Is that the correct way to convert USD to cents? because I have seen some reports with different code and not which one is correct, any ideas?

6

3 Answers

Be careful when doing arithmetic calculation in JavaScript. Especially if you are dealing with floating point.

Consider this case:

+19.99 * 100 // 1998.9999999999998
19.99 * 100 // 1998.9999999999998
parseFloat(19.99) * 100 // 1998.9999999999998

I know, right?! So I made this simple helper to help you out:

const toCent = amount => {
  const str = amount.toString()
  const [int] = str.split('.')

  return Number(amount.toFixed(2).replace('.', '').padEnd(int.length === 1 ? 3 : 4, '0'))
}

Result:

toCent(19.99) // 1999
toCent(19.9) // 1990
toCent(1.9) // 190
toCent(1999.99) // 199999

I haven't tested it yet thoroughly. Please don't copy paste my solution, at least you do your own test.

2

The way you are doing it now is perfectly valid. I have benchmarked your answer vs the answers from the comments and here are the results.

Winner:

const result = (parseFloat(number) * 100).toString();

Second Place (~99% of Winner):

const result = (Number(number) * 100).toString();

Third Place (~96% of Winner):

const result = (+number * 100).toString();

Fourth Place (~80% of Winner):

const result = number.replace(".", "");

As noted, your method will not work when the string does not match /\d\.\d\d/ however the other methods will work.

Tested on Safari 14

0

It's not correct if you have to transform 3.5 for example. You will get 35 cents. just do const cents = +myNumber * 100

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.