Calculate lowest common indivisible number in JavaScript

30 Views Asked by At

I am making API calls to a shipping provider.

It returns the shipping price in the following format: "4250" which is actually $42.50.

The API documentation says the following: Value in the lowest common indivisible unit of the currency. 42.50 CAD would be represented as 4250.

How would I go about using Math functions in Javascript to make this display correctly? Obviously I don't want to charge $4250 for something that is really $42.50.

1

There are 1 best solutions below

0
kelie On BEST ANSWER

// Example price from API response
const apiPrice = "4250";

// Convert to the actual currency value
const actualPrice = parseFloat(apiPrice) / 100;

// Format as currency (e.g., USD)
const formattedPrice = actualPrice.toLocaleString("en-US", { style: "currency", currency: "USD" });

console.log(formattedPrice);

You'd better not modify the numbers displayed, but let the interface return the data directly to you.