diff --git a/history.txt b/history.txt index 9562cc0..becff4d 100644 --- a/history.txt +++ b/history.txt @@ -7,6 +7,7 @@ * Minor enhancements * Fixing find("") issue (thanks epochwolf) * Altered protected attributes so that hash provided to #attributes= is not modified + * Altering typecasting for floats to better handle commas and points Notes: diff --git a/lib/couchrest/model/typecast.rb b/lib/couchrest/model/typecast.rb index 496558d..45a3114 100644 --- a/lib/couchrest/model/typecast.rb +++ b/lib/couchrest/model/typecast.rb @@ -79,7 +79,7 @@ module CouchRest # Match numeric string def typecast_to_numeric(value, method) if value.respond_to?(:to_str) - if value.to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/ + if value.gsub(/,/, '.').gsub(/\.(?!\d*\Z)/, '').to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/ $1.send(method) else value diff --git a/spec/couchrest/property_spec.rb b/spec/couchrest/property_spec.rb index 363da5b..98c0fb5 100644 --- a/spec/couchrest/property_spec.rb +++ b/spec/couchrest/property_spec.rb @@ -320,12 +320,28 @@ describe "Model properties" do @course['estimate'].should eql(-24.35) end + it 'return float of a number with commas instead of points for decimals' do + @course.estimate = '23,35' + @course['estimate'].should eql(23.35) + end + + it "should handle numbers with commas and points" do + @course.estimate = '1,234.00' + @course.estimate.should eql(1234.00) + end + + it "should handle a mis-match of commas and points and maintain the last one" do + @course.estimate = "1,232.434.123,323" + @course.estimate.should eql(1232434123.323) + end + [ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value| it "does not typecast non-numeric value #{value.inspect}" do @course.estimate = value @course['estimate'].should equal(value) end end + end describe 'when type primitive is a Integer' do