Convert dollars to cents in JavaScript
Asked Answered
P

5

5

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?

Painless answered 8/9, 2020 at 19:37 Comment(6)
const separe = Number(number) ? Number(number * 100).Yseult
Yours is also correct.Yseult
Depends on the formatting expected. Say I had 0.02, would they want 002? Or should it be 2?Fears
yes, it should be 002, And if it is an integer value, how would it be? for example $7Painless
A US dollar is equal to 100 US cents. Use that knowledge to convert the number of dollars to the number of cents.Trisomic
You'll need to know the possible set of inputs the user is allowed to make and adjust what you do. Clearly just taking the period away isn't going to work for just the string "7". But the user could even do: "75¢". If it's always #.## then your solution will work, otherwise it won't.Fears
V
10

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.

Valenza answered 27/1, 2022 at 16:18 Comment(4)
there is small bug - const int = str.split('.') instead of const [int] = str.split('.')Ahasuerus
Finally an answer that considers the IEEE floating point arithmetic. ThanksAdame
this seems too complicated, why not the toFixed(0)?Frostwork
This just works :)Clabo
D
6

This will do it with any value.

export function toCents(aValue){
  return Math.round((Math.abs(aValue) / 100) * 10000);
}
Disjoined answered 27/9, 2022 at 6:5 Comment(2)
toCents(17.49) // 1748Jeanmariejeanna
@OrionHall just updated the function.Disjoined
T
4

The way you are doing it now works, but isn't ideal. 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

Tabescent answered 8/9, 2020 at 19:49 Comment(0)
J
0

Math.round(x * 100) seems pretty safe because it will round to the nearest integer. The better options are:

  1. Always represent your amounts in cents (i.e. whole numbers) and divide into dollars when needed
  2. Use a library (such as decimal.js or Big.js)

The implementations in the above two libraries are super complex (here, here).

Jeanmariejeanna answered 30/9, 2022 at 4:17 Comment(0)
T
0

Recently I was working on an assignment where I needed to handle decimals. And looking for information I came across this explanation of why not to use Double or Float to represent currencies.

Why not use Double or Float to represent currency?

And also this article where he explains this problem.

You better work in cents, not dollars

I ended up creating a function that takes either a string or number value and converts it to cents.

function convertToCents(value) {
    // First, trim any leading and trailing whitespace from the string
    const valueStr = typeof value === 'string' ? value.trim() : value.toString();
    
    // Next, check if the value is a number
    if (isNaN(valueStr)) {
        throw new Error('The value must be a number or a string representing a number.');
    }

    // Convert the string to a floating-point number and multiply by 100 to convert to cents
    const numericValue = parseFloat(valueStr.replace(',', '.')); // Replace commas with periods if necessary
    return Math.round(numericValue * 100);
}

Everything else was handled using dinero.js

Torch answered 4/10, 2024 at 18:11 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.