Categories
JavaScript Answers

How to convert a JavaScript string variable to decimal or money?

Spread the love

Sometimes, we want to convert a JavaScript string variable to decimal or money.

In this article, we’ll look at how to convert a JavaScript string variable to decimal or money.

How to convert a JavaScript string variable to decimal or money?

To convert a JavaScript string variable to decimal or money, we can use the Intl.NumberFormat constructor.

For instance, we write

const formatter = new Intl.NumberFormat("en", {
  style: "currency",
  currency: "GBP",
});

console.log(formatter.format(1234.5));

to create the Intl.NumberFormat object by calling it with the locale string and an object with the formatting options.

'currency' formats the string as a currency number.

And currency is set to 'GBP' so the number is formatted into a GBP value.

Then we call formatter.format with the number to format to return a string with the currency number.

Conclusion

To convert a JavaScript string variable to decimal or money, we can use the Intl.NumberFormat constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *