Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to nicely format floating numbers to string without unnecessary decimal 0's

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 an unsigned 32-bit number.

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 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 lot of performance loss due to string manipulation. Can I do better with other format code?


The answers by Tom E. and Jeremy S. are unacceptable as they both arbitrarily rounds to two decimal places. Please understand the problem before answering.


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

like image 768
Pyrolistical Avatar asked Mar 31 '09 22:03

Pyrolistical


People also ask

How do you keep a float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you format floating numbers in Python?

Format float value using the round() Method in Python The round() is a built-in Python method that returns the floating-point number rounded off to the given digits after the decimal point. You can use the round() method to format the float value.

Can floats have decimal values?

If doing math with floats, you need to add a decimal point, otherwise it will be treated as an int. See the Floating point constants page for details. The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point.

What is floating decimal format?

Definition of floating decimal : a system of decimal point placement in an electronic calculator in which the decimal point is free to move automatically across the display in order to allow the maximum number of decimal places in the readout.


2 Answers

If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum 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.

like image 151
JasonD Avatar answered Sep 24 '22 23:09

JasonD


String.format("%.2f", value); 
like image 26
Jeremy Slade Avatar answered Sep 21 '22 23:09

Jeremy Slade