Converting a possibly null Double value to a String without exponent

Viewed 329

I am attempting to create a function that will output a Double as a String with the following requirements:

  1. It will not show with exponents. I believe Double.toString(dblVal) or dblVal.toString() will take care of the exponent issue.
  2. If the Double is null it will not error and will display as 'null'. I believe String.valueOf(dblVal) will take care of this automatically if the Double is null.

Here is what I have:

function doubleToString(Double dbl) {
    String strVal = null;
    if (dbl != null)
        strVal = String.valueOf(dbl);
    
    return strVal;
}

What would be the best way to achieve both requirements? I don't think String.valueOf will get rid of the exponent so should I not be using String.valueOf() and instead using dblVal.toString() and then just to a manual check before hand on whether it is null or not and if so make strVal null?

3 Answers

There is no "one" standard library method that does everything you need. The trickier part is "not showing exponents" - one way I can think of doing that is with the BigDecimal class. This covers both of your requirements:

String doubleToString(Double dbl) {
    if (dbl == null) return "null";
    else return BigDecimal.valueOf(dbl).toPlainString();
}

Example: doubleToString(1234e-100) returns 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234

I think the following code will satisfy your requirements:

public class Solution{
    public static void main(String []args) {
        
        Double dblValue1 =  null;
        System.out.println(doubleToString(dblValue1));
        
        Double dblValue2 =  Double.parseDouble("5.895E+07");
        System.out.println(doubleToString(dblValue2));
            
}

    private static String doubleToString(Double dblValue) {
               
        if (dblValue != null) return BigDecimal.valueOf(dbl).toPlainString();
        else return "null";
    }
}

Using Java 8 Optional:

String doubleToString(Double dbl) {
    return Optional.ofNullable(dbl)
            .map(d -> BigDecimal.valueOf(d).toPlainString())
            .orElse("null");
}

Although I am not sure if this is the "best way" as you asked!

Related