Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (3.4k points)

A 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 %f

232.00000000

0.18000000000

1237875192.0

4.5800000000

0.00000000

1.23450000

What I want is:

232

0.18

1237875192

4.58

0

1.2345

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

Please note that String.format(format, args...) is locale-dependent 

1 Answer

0 votes
by (3.5k points)

You can try this to print integers saved as doubles as if they are integers, and unless printing the doubles with the smallest necessary precision:

public static String fmt(double d)

{

    if(d == (long) d)

        return String.format("%d",(long)d);

    else

        return String.format("%s",d);

}

Produces:

232

0.18

1237875192

4.58

0

1.2345

And does not rely on string manipulation.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 26, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...