Method: BigDecimal#truncate

Defined in:
bigdecimal.c

#truncate(*args) ⇒ Object

truncate(n)

Truncate to the nearest integer (by default), returning the result as a BigDecimal.

BigDecimal(‘3.14159’).truncate #=> 3 BigDecimal(‘8.7’).truncate #=> 8 BigDecimal(‘-9.9’).truncate #=> -9

If n is specified and positive, the fractional part of the result has no more than that many digits.

If n is specified and negative, at least that many digits to the left of the decimal point will be 0 in the result.

BigDecimal(‘3.14159’).truncate(3) #=> 3.141 BigDecimal(‘13345.234’).truncate(-2) #=> 13300.0



2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
# File 'bigdecimal.c', line 2543

static VALUE
BigDecimal_truncate(int argc, VALUE *argv, VALUE self)
{
    ENTER(5);
    Real *c, *a;
    int iLoc;
    VALUE vLoc;
    size_t mx, pl = VpSetPrecLimit(0);

    if (rb_scan_args(argc, argv, "01", &vLoc) == 0) {
	iLoc = 0;
    }
    else {
	iLoc = NUM2INT(vLoc);
    }

    GUARD_OBJ(a, GetVpValue(self, 1));
    mx = a->Prec * (VpBaseFig() + 1);
    GUARD_OBJ(c, NewZeroWrapLimited(1, mx));
    VpSetPrecLimit(pl);
    VpActiveRound(c, a, VP_ROUND_DOWN, iLoc); /* 0: truncate */
    if (argc == 0) {
        return BigDecimal_to_i(VpCheckGetValue(c));
    }
    return VpCheckGetValue(c);
}