Method: BigDecimal#round

Defined in:
bigdecimal.c

#round(*args) ⇒ Object

round(n, mode)

Round to the nearest integer (by default), returning the result as a BigDecimal if n is specified, or as an Integer if it isn’t.

BigDecimal(‘3.14159’).round #=> 3 BigDecimal(‘8.7’).round #=> 9 BigDecimal(‘-9.9’).round #=> -10

BigDecimal(‘3.14159’).round(2).class.name #=> “BigDecimal” BigDecimal(‘3.14159’).round.class.name #=> “Integer”

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, and return value will be an Integer.

BigDecimal(‘3.14159’).round(3) #=> 3.142 BigDecimal(‘13345.234’).round(-2) #=> 13300

The value of the optional mode argument can be used to determine how rounding is performed; see BigDecimal.mode.



2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
# File 'bigdecimal.c', line 2472

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

    unsigned short sw = VpGetRoundMode();

    switch (rb_scan_args(argc, argv, "02", &vLoc, &vRound)) {
      case 0:
	iLoc = 0;
        round_to_int = 1;
	break;
      case 1:
        if (RB_TYPE_P(vLoc, T_HASH)) {
	    sw = check_rounding_mode_option(vLoc);
	}
	else {
	    iLoc = NUM2INT(vLoc);
            if (iLoc < 1) round_to_int = 1;
	}
	break;
      case 2:
	iLoc = NUM2INT(vLoc);
	if (RB_TYPE_P(vRound, T_HASH)) {
	    sw = check_rounding_mode_option(vRound);
	}
	else {
	    sw = check_rounding_mode(vRound);
	}
	break;
      default:
	break;
    }

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