Java BigDecimal to convertDoubleToBigDecimal(final Double score, final int decimalPlaces)

Here you can find the source of convertDoubleToBigDecimal(final Double score, final int decimalPlaces)

Description

convert Double To Big Decimal

License

Educational Community License

Declaration

private static BigDecimal convertDoubleToBigDecimal(final Double score, final int decimalPlaces) 

Method Source Code

//package com.java2s;
/**//from   ww  w  . j  a v  a 2 s  .c  o  m
 * Copyright (c) 2003-2017 The Apereo Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://opensource.org/licenses/ecl2
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    private static BigDecimal convertDoubleToBigDecimal(final Double score, final int decimalPlaces) {
        // Rounding is problematic due to the use of Doubles in
        // Gradebook. A number like 89.065 (which can be produced by
        // weighted categories, for example) is stored as the double
        // 89.06499999999999772626324556767940521240234375. If you
        // naively round this to two decimal places, you get 89.06 when
        // you wanted 89.07
        //
        // Payten devised a clever trick of rounding to some larger
        // decimal places first, which rounds these numbers up to
        // something more manageable. For example, if you round the
        // above to 10 places, you get 89.0650000000, which rounds
        // correctly when rounded up to 2 places.

        return new BigDecimal(score).setScale(10, RoundingMode.HALF_UP).setScale(decimalPlaces,
                RoundingMode.HALF_UP);
    }
}

Related

  1. bigDecimalToString(BigDecimal dec)
  2. convertBigDecimalTodouble(BigDecimal bigDecimalVal)
  3. convertBigDecimalToSQLBigNum(BigDecimal bd, int targetLength, int targetScale)
  4. convertBigDecimalToString(BigDecimal bigValue)
  5. convertDoubleToBigDecimal(Double value)
  6. convertFeetToInches(BigDecimal feet)
  7. convertHoursToMillis(BigDecimal hours)
  8. convertNullToBigDecimal(Object orgStr)
  9. convertRadiansToDegrees(BigDecimal radians)