APIdock / Ruby
/
method

round

ruby latest stable - Class: Time
round(p1 = v1)
public

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 positive integer.

require 'time'
t = Time .utc (2010,3,30, 5,43,"25.123456789".to_r )
p t.iso8601 (10) #=> "2010年03月30日T05:43:25.1234567890Z"
p t.round .iso8601 (10) #=> "2010年03月30日T05:43:25.0000000000Z"
p t.round (0).iso8601 (10) #=> "2010年03月30日T05:43:25.0000000000Z"
p t.round (1).iso8601 (10) #=> "2010年03月30日T05:43:25.1000000000Z"
p t.round (2).iso8601 (10) #=> "2010年03月30日T05:43:25.1200000000Z"
p t.round (3).iso8601 (10) #=> "2010年03月30日T05:43:25.1230000000Z"
p t.round (4).iso8601 (10) #=> "2010年03月30日T05:43:25.1235000000Z"
p t.round (5).iso8601 (10) #=> "2010年03月30日T05:43:25.1234600000Z"
p t.round (6).iso8601 (10) #=> "2010年03月30日T05:43:25.1234570000Z"
p t.round (7).iso8601 (10) #=> "2010年03月30日T05:43:25.1234568000Z"
p t.round (8).iso8601 (10) #=> "2010年03月30日T05:43:25.1234567900Z"
p t.round (9).iso8601 (10) #=> "2010年03月30日T05:43:25.1234567890Z"
p t.round (10).iso8601 (10) #=> "2010年03月30日T05:43:25.1234567890Z"
t = Time .utc (1999,12,31, 23,59,59)
p((t + 0.4).round .iso8601 (3)) #=> "1999年12月31日T23:59:59.000Z"
p((t + 0.49).round .iso8601 (3)) #=> "1999年12月31日T23:59:59.000Z"
p((t + 0.5).round .iso8601 (3)) #=> "2000年01月01日T00:00:00.000Z"
p((t + 1.4).round .iso8601 (3)) #=> "2000年01月01日T00:00:00.000Z"
p((t + 1.49).round .iso8601 (3)) #=> "2000年01月01日T00:00:00.000Z"
p((t + 1.5).round .iso8601 (3)) #=> "2000年01月01日T00:00:01.000Z"
t = Time .utc (1999,12,31, 23,59,59)
p (t + 0.123456789).round (4).iso8601 (6) #=> "1999年12月31日T23:59:59.123500Z"
static VALUE
time_round(int argc, VALUE *argv, VALUE time)
{
 VALUE ndigits, v, a, b, den;
 long nd;
 struct time_object *tobj;
 rb_scan_args(argc, argv, "01", &ndigits);
 if (NIL_P(ndigits))
 ndigits = INT2FIX(0);
 else
 ndigits = rb_to_int(ndigits);
 nd = NUM2LONG(ndigits);
 if (nd < 0)
 rb_raise(rb_eArgError, "negative ndigits given");
 GetTimeval(time, tobj);
 v = w2v(rb_time_unmagnify(tobj->timew));
 a = INT2FIX(1);
 b = INT2FIX(10);
 while (0 < nd) {
 if (nd & 1)
 a = mulv(a, b);
 b = mulv(b, b);
 nd = nd >> 1;
 }
 den = quov(INT2FIX(1), a);
 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);
}

AltStyle によって変換されたページ (->オリジナル) /