Home >Java >javaTutorial >How Can I Print Doubles in Java with Precise Formatting, Eliminating Unnecessary Trailing Zeros?
Given the ability of a 64-bit double to represent integers precisely within a range, a challenge arises when printing mixed integer and double values. While String.format("%f") provides close formatting, it adds unnecessary trailing zeros for small values.
Seeking a Solution:
The goal is to print integer values stored as doubles without decimal zeros, while maintaining high precision for actual doubles. For instance, given these inputs:
The desired output would be:
Efficient Formatting:
To optimize formatting, we can exploit the fact that integer values can be represented precisely as 64-bit doubles. The following Java code snippet achieves this without resorting to performance-intensive string manipulation:
public static String fmt(double d) { if (d == (long) d) return String.format("%d", (long) d); else return String.format("%s", d); }
Explanation:
Result:
When applied to the example inputs, the output matches the desired format:
232 0.18 1237875192 4.58 0 1.2345
The above is the detailed content of How Can I Print Doubles in Java with Precise Formatting, Eliminating Unnecessary Trailing Zeros?. For more information, please follow other related articles on the PHP Chinese website!