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
// 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);
};
requires protoype (but really shouldn’t) FYI
great 😀
no as elegant as ruby, but if it works i wont complain 🙂
parts[0] = parts[0].reverse.gsub(/.{3}/, ‘.’.reverse)
appears to be almost twice as fast as the gsub line above.
Maybe turning this into a gist with some tests + benchmarks would be helpful, otherwise I touching it seems danergous 🙂