Myoch
Myoch

Reputation: 845

Precision when Casting from Double to Float while concatenating String?

I recently ran in the following curiosity:

    double d=0.8608278036117554;
    String precision="float";

    float f=(float)d;
    String s="a " + (precision.equals("float") ? (float)d: d) + " Bonjour";
    String s2="a " + String.valueOf(precision.equals("float") ? (float)d: d) + " Bonjour";
    String s3="a " + (precision.equals("float") ? String.valueOf((float)d): String.valueOf(d)) + " Bonjour";


    println(d);
    println(f);
    println(s);
    println(s2);
    println(s3);


//0.8608278036117554
//0.8608278
//a 0.8608278036117554 Bonjour
//a 0.8608278036117554 Bonjour
//a 0.8608278 Bonjour

Why is it not possible to have a nice float when computing s or s2 ? Why is it still a double in case s and s2?

PS: This question has nothing to do with number formatting, in my opinion. I really want to understand why is the (float)d cast not working!!

Upvotes: 0

Views: 54

Answers (1)

Holger
Holger

Reputation: 298103

Your expression precision.equals("float") ? (float)d: d has no effect, as the conditional operator has one single resulting type, which is double if one argument has the type float and the other has the type double.

So the first alternative will be widened from float to double and while the conversion from double to float and back to double may have an effect on the value, String.valueOf(double) will be called in either case.

You can use (precision.equals("float") ? String.valueOf((float)d): String.valueOf(d)) instead, whose method invocations are not redundant, as they are invocations of different methods, String.valueOf(float) and String.valueOf(double).

That said, you should not use narrowing to float to control the output. Check Format Float to n decimal places for alternatives which provide more control over the formatted output.

Upvotes: 3

Related Questions