Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currency Formatting in JavaScript [duplicate]

Possible Duplicate:
How can I format numbers as money in JavaScript?

I have a form with some simple JavaScript to perform an instant calculation. My problem is that I'm struggling to format it to display correctly with commas and 2 decimal places.

Any help would be very much appreciated. Thank you.

    <p>     <label>My Daily Rate is:</label><br /> <input class="poundsBox" name="shares" id="shares" type="text" /><br /> <br /> <strong>Your Gross Contract Take Home:</strong></p> <p><span class="result">&pound; <span id="result"></span></span></p> The above illustration is provided for guidance only. Please complete the request form below for a detailed personal illustration.  <script type="text/javascript"> $("#shares").keyup(function() {    var val = parseFloat($(this).val());    // If val is a good float, multiply by 260, else show an error    val = (val ? val * 260 * 0.88 : "Invalid number");    $("#result").text(val); }) </script> 
like image 249
kevg Avatar asked Jan 22 '13 20:01

kevg


People also ask

How do you format numbers in JavaScript?

The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in above syntax using the '. ' operator.

What is Intl NumberFormat?

Intl.NumberFormat.prototype.format() Getter function that formats a number according to the locale and formatting options of this Intl.NumberFormat object. Intl.NumberFormat.prototype.formatToParts() Returns an Array of objects representing the number string in parts that can be used for custom locale-aware formatting.


2 Answers

You can use standard JS toFixed method

var num = 5.56789; var n=num.toFixed(2);  //5.57 

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")  //100000 => 100,000 //8000 => 8,000 //1000000 => 1,000,000 

Complete example:

var value = 1250.223; var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");  //document.write(num) would write value as follows: $1,250.22 

Separation character depends on country and locale. For some countries it may need to be .

like image 190
Tom Avatar answered Sep 21 '22 19:09

Tom


You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?

like image 33
Harish Avatar answered Sep 21 '22 19:09

Harish