Issue #7829 has been updated by loirotte (Philippe Dosch).


akr (Akira Tanaka) wrote:

>  2. Time.strftime("%L") doesn't round, but floor.
>  
>    %L (and %N) in Time.strftime doesn't round the value but floor the value.
>  
>    Since 3-digits under the point of
>  0.8599999999999994315658113919198513031005859375
>    is "859", %L shows "859".
>  
>    rounding is not appropriate here.
>    It is clearely unexpected that %L for 0.99999 shows "1000".

Understood. Just surprised that floor is used instead of round in this situation!
 
>  3. Use Time#round.
>  
>    There is a method to rounding Time: Time#round.
>  
>    If you needs a Time value rouinding 3-digits under the second,
>    use time.round(3).
>  
>    % ruby -e 'p Time.utc(1970,1,1,0,0,12.860).round(3).strftime("%H:%M:%S,%L")'
>    "00:00:12,860"

It fixes my personal issue in a first time, thanks!

Philippe

----------------------------------------
Bug #7829: Rounding error in Ruby Time
https://bugs.ruby-lang.org/issues/7829#change-36163

Author: loirotte (Philippe Dosch)
Status: Open
Priority: Normal
Assignee: 
Category: DOC
Target version: next minor
ruby -v: ruby 1.9.3p194 (2012-04-20 revision 35410) [i686-linux]


Even if I know the precision errors related to the implementation of IEEE 754 floating values, I'm very surprised of:

irb(main):001:0> Time.utc(1970,1,1,0,0,12.860).strftime("%H:%M:%S,%L")
=> "00:00:12,859"

The fact is that I obtain:

irb(main):002:0> Time.utc( 1970, 1, 1, 0, 0, 12.860 ).subsec
=> (60517119992791/70368744177664)
irb(main):003:0> Time.utc( 1970, 1, 1, 0, 0, 12.860 ).subsec.to_f
=> 0.8599999999999994

If I well understand the precision error that is reported for the 12th or 14th digit after the comma, I don't understand why the rounding process gives an unexpected result for this value. In this case, the last significant digit of my value is impacted, and it appears to be a embarrassing behavior. For other values, the obtained result is as expected:

irb(main):001:0> Time.utc(1970,1,1,0,0,12.880).strftime("%H:%M:%S,%L")
=> "00:00:12,880"

Moreover, this is a part of the Time class and I don't know any way to fix it in a program (and I don't know the full list of values reproducing this issue...)


-- 
http://bugs.ruby-lang.org/