Спочатку double призначений для наукових розрахунків, де округлення практично не використовується, оскільки навпаки - потрібна максимально допустима точність.
А ось для фінансових і тому подібних розрахунків призначений клас BigDecimal, де результат може бути представлений абсолютно точно. Ось там є все необхідне, в тому числі, і для округлення потрібним методом і розрядністю.
Зате в BigDecimal немає ніяких sin & cos, які у фінансах не використовуються.
1 спосіб
double d = 12.1354678578862;
d = d * 1000;
int i = (int) Math.round(d);
d = (double)i / 1000;
2 спосіб через RoundingMode
double newDouble = new BigDecimal(templateDouble).setScale(3, RoundingMode.UP).doubleValue();}
Rounding mode to round away from zero. Always increments the digit prior to a nonzero discarded fraction. Note that this rounding mode never decreases the magnitude of the calculated value.
BigDecimal.ROUND_DOWN
Rounding mode to round towards zero. Never increments the digit prior to a discarded fraction (i.e., truncates). Note that this rounding mode never increases the magnitude of the calculated value.
BigDecimal.ROUND_CEILING
Rounding mode to round towards positive infinity. If the BigDecimal is positive, behaves as for ROUND_UP; if negative, behaves as for ROUND_DOWN. Note that this rounding mode never decreases the calculated value.
BigDecimal.ROUND_FLOOR
Rounding mode to round towards negative infinity. If the BigDecimal is positive, behave as for ROUND_DOWN; if negative, behave as for ROUND_UP. Note that this rounding mode never increases the calculated value.
BigDecimal.ROUND_HALF_UP
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is >= 0.5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.
ROUND_HALF_DOWN
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. Behaves as for ROUND_UP if the discarded fraction is > 0.5; otherwise, behaves as for ROUND_DOWN.
BigDecimal.ROUND_HALF_EVEN
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.
BigDecimal.ROUND_UNNECESSARY
Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary. If this rounding mode is specified on an operation that yields an inexact result, an ArithmeticException is thrown.
Немає коментарів:
Дописати коментар