Home >Java >javaTutorial >How Can I Print Doubles in Java with Precise Formatting, Eliminating Unnecessary Trailing Zeros?

How Can I Print Doubles in Java with Precise Formatting, Eliminating Unnecessary Trailing Zeros?

Barbara Streisand
Barbara StreisandOriginal
2024-12-31 13:41:11615browse

How Can I Print Doubles in Java with Precise Formatting, Eliminating Unnecessary Trailing Zeros?

Printing Floating Numbers with Precision in Java

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:

  • 232.00000000
  • 0.18000000000
  • 1237875192.0
  • 4.5800000000
  • 0.00000000
  • 1.23450000

The desired output would be:

  • 232
  • 0.18
  • 1237875192
  • 4.58
  • 0
  • 1.2345

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:

  • For integer values that can be accurately represented as doubles, the code converts them to long and formats them using %d. This eliminates unnecessary trailing zeros.
  • For non-integer values, the code uses %s to preserve the original double value with minimal precision.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn