Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #11409 (closed defect: fixed)

Opened 7 months ago

Last modified 7 months ago

[PATCH] Fixes for number_with_precision and number_to_currency

Reported by: zhangyuanyi Assigned to: core
Priority: normal Milestone: 2.x
Component: ActionPack Version: edge
Severity: normal Keywords:
Cc:

Description

This patch try to fix the bug in ticket #8027 and #8275, they are both caused by Ruby's sprintf bug:

irb> "%01.2f" % "31.825" 
=> "31.82"
irb> "%01.2f" % "32.825"
=> "32.83"

#8275 provides a solution to initial number with BigDecimal, but it only work for Mac,

My solution is round the number before pass them to sprintf, and I've tested that it works for both Mac, Windows and Linux:

def number_with_precision(number, precision=3)
  "%01.#{precision}f" % ((Float(number) * (10 ** precision)).round.to_f / 10 ** precision)
end

irb>  number_with_precision(31.825, 2)
=> "31.83"
irb>  number_with_precision(32.825, 2)
=> "32.83"

Attachments

number_with_precision_fix.diff (1.4 kB) - added by zhangyuanyi on 03/24/08 10:59:47.
Fix of number_with_precision and number_to_currency

Change History

03/24/08 10:59:47 changed by zhangyuanyi

  • attachment number_with_precision_fix.diff added.

Fix of number_with_precision and number_to_currency

03/24/08 13:00:46 changed by Henrik N

Also see http://dev.rubyonrails.org/ticket/10090#comment:1 which mentions round-to-even. Quickly glancing at this issue suggests that's not the case here, but mentioning it just in case.

03/24/08 21:12:59 changed by david

  • status changed from new to closed.
  • resolution set to fixed.

(In [9086]) Fixed NumberHelper#number_with_precision to properly round in a way that works equally on Mac, Windows, Linux (closes #11409, #8275, #10090, #8027) [zhangyuanyi]