Method: Time#round
- Defined in:
- time.c
#round([ndigits]) ⇒ Time
Rounds sub seconds to a given precision in decimal digits (0 digits by default). It returns a new Time object. ndigits should be zero or a positive integer.
require 'time'
t = Time.utc(2010,3,30, 5,43,25.123456789r)
t.iso8601(10) #=> "2010-03-30T05:43:25.1234567890Z"
t.round.iso8601(10) #=> "2010-03-30T05:43:25.0000000000Z"
t.round(0).iso8601(10) #=> "2010-03-30T05:43:25.0000000000Z"
t.round(1).iso8601(10) #=> "2010-03-30T05:43:25.1000000000Z"
t.round(2).iso8601(10) #=> "2010-03-30T05:43:25.1200000000Z"
t.round(3).iso8601(10) #=> "2010-03-30T05:43:25.1230000000Z"
t.round(4).iso8601(10) #=> "2010-03-30T05:43:25.1235000000Z"
t = Time.utc(1999,12,31, 23,59,59)
(t + 0.4).round.iso8601(3) #=> "1999-12-31T23:59:59.000Z"
(t + 0.49).round.iso8601(3) #=> "1999-12-31T23:59:59.000Z"
(t + 0.5).round.iso8601(3) #=> "2000-01-01T00:00:00.000Z"
(t + 1.4).round.iso8601(3) #=> "2000-01-01T00:00:00.000Z"
(t + 1.49).round.iso8601(3) #=> "2000-01-01T00:00:00.000Z"
(t + 1.5).round.iso8601(3) #=> "2000-01-01T00:00:01.000Z"
t = Time.utc(1999,12,31, 23,59,59)
(t + 0.123456789).round(4).iso8601(6) #=> "1999-12-31T23:59:59.123500Z"
4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 |
# File 'time.c', line 4293
static VALUE
time_round(int argc, VALUE *argv, VALUE time)
{
VALUE ndigits, v, den;
struct time_object *tobj;
if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
den = INT2FIX(1);
else
den = ndigits_denominator(ndigits);
GetTimeval(time, tobj);
v = w2v(rb_time_unmagnify(tobj->timew));
v = modv(v, den);
if (lt(v, quov(den, INT2FIX(2))))
return time_add(tobj, time, v, -1);
else
return time_add(tobj, time, subv(den, v), 1);
}
|