Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a functionality in JavaScript to convert values into specific locale formats?

Is there a built in function of JavaScript to convert a string into a particular locale (Euro in my case)?

E.g. 50.00 should get converted to 50,00 €.

like image 980
Murtaza Mandvi Avatar asked Mar 15 '11 15:03

Murtaza Mandvi


People also ask

What does the toLocaleString () method do in JS?

The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .

How do I localize a number in JavaScript?

In JavaScript, toLocaleString() is a Number method that is used to convert a number into a locale-specific numeric representation of the number (rounding the result where necessary) and return its value as a string.

What is locale JavaScript?

Locale (Runtime - JavaScript) A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user.


2 Answers

I found a way to do this at this page.

You can you toLocaleString without using toFixed before it. toFixed returns a string, toLocaleString should get a number. But you can pass an options object with toLocaleString, the option minimumFractionDigits could help you with the functionality toFixed has.

50.toLocaleString('de-DE', {     style: 'currency',      currency: 'EUR',      minimumFractionDigits: 2  }); 

Checkout all the other options you can pass with this function.

like image 185
Willem de Wit Avatar answered Oct 11 '22 13:10

Willem de Wit


50.00 is a unit-less value. The best you can do is convert 50.00 to 50,00 and then append the yourself. Therefore, just use Number.toLocaleString().

var i = 50.00; alert(i.toLocaleString() + ' €'); // alerts '50.00 €' or '50,00 €' 

Demo →

Lots of relevant questions:

  • How can I format numbers as money in JavaScript? (the big one; ~70k views)
  • Convert to currency format
  • Format currency using javascript
  • how do i print currency format in javascript
  • JavaScript: Format number/currency w/regards to culture like .NET's String.Format()? (possibly useful, if you're using ASP.NET)
  • format number to price
like image 34
Matt Ball Avatar answered Oct 11 '22 14:10

Matt Ball