Bruno
Bruno

Reputation: 1055

Formatting numbers for currency in js

I want to format numbers to currency format and I'm trying as follows. I present two examples:

var numero = 1274.78;
var numero1 = 12740.78;
var myObj = {
  style: "currency",
  currency: "EUR"
}

console.log(numero.toLocaleString("pt-PT", myObj));

console.log(numero1.toLocaleString("pt-PT", myObj));

In the second example it correctly formats the number, but in the first example it doesn't. As you already have thousands of thousands, you should format the number as follows 1 274.78 € and not as you are formatting it.

Upvotes: 0

Views: 98

Answers (1)

Adamszsz
Adamszsz

Reputation: 581

You can do something like that use numberWithSpaces function:

    var numero = 1274.78;
    var numero1 = 12740.78;
    var myObj = {
      style: "currency",
      currency: "EUR"
    }
    
    
    function numberWithSpaces(x) {
        var parts = x.toString().split(".");
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        return parts.join(".");
    }
    
   console.log(numberWithSpaces(numero).toLocaleString("pt-PT", myObj));

   console.log(numberWithSpaces(numero1).toLocaleString("pt-PT", myObj));

The result is : enter image description here

Upvotes: 1

Related Questions