Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 573
Ali Avatar asked Dec 11 '25 04:12

Ali


2 Answers

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 */
like image 124
Emad Dehnavi Avatar answered Dec 13 '25 16:12

Emad Dehnavi


You can use toLocaleString to add the commas to the number.

var number = 45000;
var formatted = '$' + number.toLocaleString(); // $45,000

number = 500999.12345;
formatted = '$' + number.toLocaleString(); // $500,999.12345

EDIT: To prevent rounding, use minimumFractionDigits option:

number.toLocaleString(undefined, { minimumFractionDigits: 20 });

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Related to this question.

like image 25
justin Avatar answered Dec 13 '25 17:12

justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!