Search code examples
jquerycurrency

How to convert a value to currency format with 2 decimals?


How can I convert the last 2 numbers of a given value as the decimals of a currency value?

Sample: 2499 should come out as 24,99 and not 2,499.00 what I am currently getting.

var price = $('.album').data("totalprice");
    
var newPrice = price.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');

console.log(newPrice);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="album" data-totalprice="2499"></div>


Solution

  • Use Intl.NumberFormat after dividing the amount by 100

    const n = 2499;
    const f = new Intl.NumberFormat('de-DE', {
      style: 'currency',
      currency: 'EUR'
    }).format(n / 100);
    console.log(f);

    See the different parameters available here. Of course you can also use Schweizer Franken as your currency