javascriptcurrency

Javascript display currency without rounding


I am displaying currency values in javascript, I want to display $ with every value and I also want , (comma) for thousands but I don't want rounding of digits after decimal point and I also don't have a fixed limit of how many digits would be after decimal point.

It is for en-AU

for example

45000 -> $45,000

3.6987 -> $3.6987

3 -> $3

4.00 -> $4.00

Is there any built-in JavaScript method or library can help to achieve this?


Solution

  • I Suggest to use Intl.NumberFormat

    var formatter = new Intl.NumberFormat('en-US', {
       style: 'currency',
       currency: 'USD',
       minimumFractionDigits: 2,      
    });
    
    formatter.format(3242); /* $3,242.00 */
    

    You can config your FractionDigits and even your currency sign :

    var formatter = new Intl.NumberFormat('en-US', {
       style: 'currency',
       currency: 'GBP',
       minimumFractionDigits: 4,      
    });
    
    formatter.format(3242); /* £3,242.0000 */
    

    UPDATE :

    if you can't fixed your fraction digits you can use maximumFractionDigits and give it an amount of 20 and also give minimumFractionDigits value of 0 :

    var formatter = new Intl.NumberFormat('en-US', {
       style: 'currency',
       currency: 'GBP',
       minimumFractionDigits: 0,
       maximumFractionDigits: 20,
    });
    
    formatter.format(3242.5454); /* £3,242.5454 */