views:

1971

answers:

3

An 64-bit double can represent integer +/- 253 exactly

Given this fact I choose to use a double type as a single type for all my types, since my largest integer is unsigned 32-bit.

But now I have to print these pseudo integers, but the problem is they are also mixed in with actual doubles.

So how do I print these doubles nicely in Java?

I have tried String.format("%f", value), which is close, except I get a lot of trailing zeros for small values.

Here's an example output of of %f

232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000

Sure I can write a function to trim those zeros, but that's lot of performance loss due to String manipulation. Can I do better with another format code?

+1  A: 

Naw, never mind.

Performance loss due to String manipulation is zero.

And here's the code to trim the end after %f

private static String trimTrailingZeros(String number) {
    if(!number.contains(".")) {
        return number;
    }

    number = number.replaceAll("0*$", "");
    if(number.charAt(number.length() - 1) == '.') {
        number = number.substring(0, number.length() - 1);
    }
    return number;
}
Pyrolistical
If you are going to down vote, you need to at least leave a comment
Pyrolistical
I downvoted because your solution is not the best way to go. Have a look at String.format. You need to use the correct format type, float in this instance. Look at my above answer.
jjnguy
A: 

I think formatting is what java.text.DecimalFormat is for.

duffymo
+5  A: 

String.format("%.2f",value)

Jeremy Slade
That's correct but always prints trailing zeros even if there is no fractional part. String.format("%.2f, 1.0005) prints 1.00 and not 1. Is there any format specifier for not to print fractional part if it does not exist?
eyazici