Numbers for Humans – Humanize for Numeric

number_with_precision(result.round(2)) — BE GONE!

Usage
1.humanize == “1”
1000000.humanize == “1.000.000”
1000.12345.humanize == “1.000,12”

Install

#config/initializers/numeric_humanize.rb
class Numeric
  def humanize(rounding=2,delimiter=',',separator='.')
    value = respond_to?(:round_with_precision) ? round(rounding) : self
    
    #see number with delimeter
    parts = value.to_s.split('.')
    parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
    parts.join separator
  end
end
Advertisements

5 thoughts on “Numbers for Humans – Humanize for Numeric

  1. // Ported to Javascript

    Number.prototype.humanize = function(rounding, delimiter, separator){
    rounding = (typeof rounding != ‘undefined’) ? rounding : 2;
    delimiter = (typeof delimiter != ‘undefined’) ? delimiter : ‘,’;
    separator = (typeof separator != ‘undefined’) ? separator : ‘.’;

    var value = (function(value){
    if (rounding == 0) return Math.round(value);
    var round_by = Math.pow(10,rounding);
    return (Math.round( value * (round_by) ) / round_by);
    })(this);

    parts = value.toString().split(‘.’);
    parts[0] = parts[0].gsub(/(\d)(?=(\d\d\d)+(?!\d))/, “#{1}”+delimiter);
    return parts.join(separator);
    };

  2. parts[0] = parts[0].reverse.gsub(/.{3}/, ‘.’.reverse)
    appears to be almost twice as fast as the gsub line above.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s