convert double To String and round up - Java java.lang

Java examples for java.lang:double Format

Description

convert double To String and round up

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        double value = 42.45678;
        boolean roundUp = true;
        System.out.println(convertToString(value, roundUp));
    }/*from   ww  w.  ja  v  a 2 s. co m*/

    /**
     * @param value
     * @param roundUp
     * @return
     */
    public static String convertToString(Double value, Boolean roundUp) {

        String[] split = Double.toString(value).split("\\.");

        return cleanUpString(split, roundUp);
    }

    /**
     * @param value
     * @param roundUp
     * @return
     */
    public static String convertToString(int value, Boolean roundUp) {

        String[] split = Integer.toString(value).split("\\.");

        return cleanUpString(split, roundUp);
    }

    /**
     * @param split
     * @param roundUp
     * @return
     */
    private static String cleanUpString(String[] split, Boolean roundUp) {
        String moneyString = "$" + split[0];
        if (!roundUp) {
            String remainder = split[1];
            if (remainder.length() == 1) {
                remainder.concat("0");
            } else if (remainder.length() < 2) {
                //TODO need to remove any "extra" values after the second number.
            }
            moneyString.concat("." + remainder);
        }

        return moneyString;
    }
}

Related Tutorials