1
jQuery(function() { jQuery( "#slider-range-min" ).slider({ range: "min", value: 1, step: 1000, min: 100000, max: 3000000, slide: function( event, ui ) { jQuery( "#amount" ).val( "$" + ui.value ); } }); jQuery( "#amount" ).val( "$" + $( "#slider-range-min" ).slider( "value" ) ); }); 

The field "amount" on our page is filled with the value, but we want this value to be formatted similar to PHPs number_format (with commas, etc).

How would I go about doing this in javascript?

1
  • 1
    Incidentally, this has nothing to do with jQuery. Commented Apr 24, 2011 at 7:27

3 Answers 3

2

you can use two native javascript functions for this.

toPrecision()

var num = new Number(65.823474); var result = num.toPrecision(2); // 65 

toFixed()

var num = new Number(65.823474); var result = num.toFixed(2); // 65.82 

However, it does not add the (localized) comma's.

Depending on the culture you are writing for you should replace/insert dots and comma's.

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatives to calling the Number function as a constructor are: Number(65.823474).toPrecision(2) and simply (65.823474).toPrecision(2).
0
function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } 

Ref : http://www.mredkj.com/javascript/numberFormat.html

1 Comment

ntt.cc/2008/04/25/… can also help you
0

here i found a pretty good script to format numeric data in javascript, googling a little bit. The code is a little too large, so here's the link to the author's article:

How to format numbers in JavaScript flexibly and efficiently

The sole thing with it is it uses prototype, so its not "pure" javascript... hope you can use it!

1 Comment

For scripts to deal with numbers and dates, use: merlyn.demon.co.uk/#jav

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.