Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Currency Format Number

I have number like this in my html

<div class="number">950000</div>

and I want jQuery change it to

<div class="number">Rp. 950.000</div>

How can I do that in jQUery?

like image 947
GusDeCooL Avatar asked Apr 27 '11 16:04

GusDeCooL


People also ask

How do you format currency value?

On the Home tab, click the Dialog Box Launcher next to Number. Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting. In the Symbol box, click the currency symbol that you want.

How do you format numbers in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.


2 Answers

Divide by 1000, and use .toFixed(3) to fix the number of decimal places.

var output = (input/1000).toFixed(3); 

[EDIT]

The above solution only applies if the dot in the original question is for a decimal point. However the OP's comment below implies that it is intended as a thousands separator.

In this case, there isn't a single line solution (Javascript doesn't have it built in), but it can be achieved with a fairly short function.

A good example can be found here: http://www.mredkj.com/javascript/numberFormat.html#addcommas

Alternatively, a more complex string formatting function which mimics the printf() function from the C language can be found here: http://www.diveintojavascript.com/projects/javascript-sprintf

like image 84
Spudley Avatar answered Sep 23 '22 13:09

Spudley


Here is the cool regex style for digit grouping:

thenumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
like image 41
ihsan Avatar answered Sep 22 '22 13:09

ihsan