Method: Float#truncate
- Defined in:
- numeric.c
#truncate(ndigits = 0) ⇒ Float, Integer
Returns self truncated (toward zero) to a precision of ndigits decimal digits.
When ndigits is positive, returns a float with ndigits digits after the decimal point (as available):
f = 12345.6789
f.truncate(1) # => 12345.6
f.truncate(3) # => 12345.678
f = -12345.6789
f.truncate(1) # => -12345.6
f.truncate(3) # => -12345.678
When ndigits is negative, returns an integer with at least ndigits.abs trailing zeros:
f = 12345.6789
f.truncate(0) # => 12345
f.truncate(-3) # => 12000
f = -12345.6789
f.truncate(0) # => -12345
f.truncate(-3) # => -12000
Note that the limited precision of floating-point arithmetic may lead to surprising results:
(0.3 / 0.1).truncate #=> 2 (!)
Related: Float#round.
2697 2698 2699 2700 2701 2702 2703 2704 |
# File 'numeric.c', line 2697 static VALUE flo_truncate(int argc, VALUE *argv, VALUE num) { if (signbit(RFLOAT_VALUE(num))) return flo_ceil(argc, argv, num); else return flo_floor(argc, argv, num); } |