Java BigDecimal to toDouble(final BigDecimal b)

Here you can find the source of toDouble(final BigDecimal b)

Description

to Double

License

Apache License

Declaration

public static Double toDouble(final BigDecimal b) 

Method Source Code


//package com.java2s;
/*//from w w  w .  j ava  2 s  .c  om
 * Copyright 2017 stanislawbartkowski@gmail.com  
 * Licensed under the Apache 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://www.apache.org/licenses/LICENSE-2.0 
 * 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;

public class Main {
    public static double toDouble(String s) {
        double d = Double.valueOf(s);
        return d;
    }

    public static Double toDouble(final BigDecimal b) {
        if (b == null) {
            return null;
        }
        String s = DecimalToS(b);
        return new Double(s);
    }

    public static String DecimalToS(final BigDecimal c, int afterdot) {
        BigDecimal cx = c.setScale(afterdot, BigDecimal.ROUND_HALF_UP);
        String ss = cx.toPlainString();
        int pos = ss.indexOf('.');
        String aDot = "";
        if (pos >= 0) {
            aDot = ss.substring(pos + 1);
            ss = ss.substring(0, pos);
        }
        if (afterdot <= 0) {
            return ss;
        }
        if (aDot.length() > afterdot) {
            aDot = aDot.substring(0, afterdot);
        }
        while (aDot.length() < afterdot) {
            aDot += "0";
        }
        return ss + "." + aDot;
    }

    public static String DecimalToS(final BigDecimal c) {
        return DecimalToS(c, 2);
    }
}

Related

  1. decimalToString(BigDecimal value)
  2. toBeforeDecimalPointString(BigDecimal bigDecimal)
  3. toDouble(BigDecimal b, boolean allownull)
  4. toDouble(BigDecimal bigDecimal)
  5. toDouble(final BigDecimal b)
  6. toInteger(BigDecimal b)
  7. toLong(BigDecimal value)
  8. toLongObject(@Nullable final BigDecimal value)
  9. toNumber(final BigDecimal bigDecimal, final Class clazz)