Java BigDecimal to toString(BigDecimal value, int numberDecimalPlaces)

Here you can find the source of toString(BigDecimal value, int numberDecimalPlaces)

Description

to String

License

Apache License

Declaration

public static String toString(BigDecimal value, int numberDecimalPlaces) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.math.BigDecimal;

public class Main {

    public static String toString(BigDecimal value, int numberDecimalPlaces) {
        String newStr = null;//w ww.  jav  a 2s  . c o m
        if (value != null) {
            try {
                newStr = String.format("%." + numberDecimalPlaces + "f", value);
                int posCorte = newStr.lastIndexOf(".");
                if (posCorte >= 0) {
                    String decimal = newStr.substring(posCorte + 1);
                    if (decimal.length() > numberDecimalPlaces) {
                        decimal = decimal.substring(0, numberDecimalPlaces);
                        newStr = newStr.substring(0, posCorte) + "." + decimal;
                    }
                }
            } catch (IllegalArgumentException e) {
                newStr = "0";
            }
        }
        return newStr;
    }

    public static String toString(BigDecimal value, int numberDecimalPlaces, boolean optional) {
        String newStr = null;
        boolean isOptionalAndValueZeroed = (optional && value != null && value.signum() == 0);
        if (isOptionalAndValueZeroed) {
            newStr = null;
        } else {
            newStr = toString(value, numberDecimalPlaces);
        }
        return newStr;
    }
}

Related

  1. toObject(BigDecimal value)
  2. toPercent(final BigDecimal decimalValue, final MathContext mathCntext)
  3. toScientificNotation(BigDecimal bd)
  4. toSimpleBigDecimal(Object num)
  5. toString(BigDecimal num)
  6. toString(final BigDecimal dec)
  7. toUnsignedString(BigDecimal bigDecimal, int shift)