0

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.

2
  • 3
    1274,78 is the expected format for the Portugese locale. If you want 1 274,78, try using the fr-FR locale. Commented Jul 30, 2021 at 10:54
  • @Niet the Dark Absol Thanks, so it already prints correctly. Commented Jul 30, 2021 at 10:59

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.