Skip to content
Advertisement

How make VueJS understand localized numbers?

Let’s figure a simple sum app. two inputs, a and b and a c result.

we have this markup

JavaScript

and this Vue script

JavaScript

this works great except that I’m working with localized numbers. that means. using comma “,” instead of dot “.” and dot instead of comma .

entering number with decimal places confuses vue, and it are not able to make a correct sum.

What can I do in order to make VueJS understand localized number input and them make the correct sum?

for instance in pt-BR locale: 1.000,30 + 100,30 = 1.100,60

Advertisement

Answer

Well, first of all, a number is just a number. Internally, the . will always be the decimal separator.

So a number like 1.100,60 is the number 1100.60 just printed in a different locale.

To print it, just use JavaScript’s Number#toStringLocale():

JavaScript
JavaScript

Using a formatted <input>

Now, if you want the <input> to take localized numbers, that is not a problem specific to Vue, but to JavaScript and the browser in general. This means that you’ll have to find a custom component that implements the behavior you want (formatting in the <input>).

Luckily, a quick search brings one that seems to to the job:

JavaScript
JavaScript

Again, the component just changes the input field. The number will still be just a number and the “printing” will still have to be done using .toLocaleString().

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement