Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a number 1000 as "1 000"

I need a way to format numbers. I stored some numbers in my DB table, e.g. 12500, and would like to print them in this format 12 500 (so there is a space every 3 digits). Is there an elegant way to do this?

like image 826
user1946705 Avatar asked Jun 23 '11 18:06

user1946705


People also ask

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.

How do I display numbers with commas in HTML?

The toLocaleString method lets us format a number to a string with commas as thousands of separators automatically. You can do HTML input number format comma with it. Or using autoNumeric plugin you can make a field as numeric input with different separators.


2 Answers

see: http://www.justskins.com/forums/format-number-with-comma-37369.html

there is no built in way to it ( unless you using Rails, ActiveSupport Does have methods to do this) but you can use a Regex like

formatted_n = n.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse 
like image 153
loosecannon Avatar answered Sep 21 '22 05:09

loosecannon


Activesupport uses this regexp (and no reverse reverse).

10000000.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1 ") #=> "10 000 000" 
like image 26
steenslag Avatar answered Sep 21 '22 05:09

steenslag