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?
相关问题
- Keeping track of variable instances
- How to get the maximum of more than 2 numbers in V
- F#: Storing and mapping a list of functions
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
- Accessing an array element when returning from a f
So, this is pretty crazy and hackish, but it gets the job done...
I just stumbled on this thread while looking for a way to format a value as US currency. I took a slightly different approach to the regex solutions proposed:
This could be parameterized for formatting other currencies.
The official document suggests three different ways:
1) Using lookbehind and lookahead (Requires oniguruma)
2) Using only lookahead. Identical to steenslag's answer.
3) Using neither lookahead nor lookbehind
Here's another method that is fairly clean and straightforward if you are dealing with integers:
Works great for integers. Of course, this particular example will separate the number by commas, but switching to spaces or any other separator is as simple as replacing the parameter in the
join
method.Another way:
You can always Open the Fixnum class and add this for convenience:
All but one of the answers use
n.to_s
. @MrMorphe's does not, but he creates an array to bejoin
ed. Here's a way that uses neither Fixnum#to_s nor Array#join.Hmmm. Is that column on the right tipping?
Another way that uses
to_s
but notjoin
: