Home > Java > javaTutorial > How Can I Elegantly Format Floating-Point Numbers in Java Without Unnecessary Decimal Zeros?

How Can I Elegantly Format Floating-Point Numbers in Java Without Unnecessary Decimal Zeros?

Patricia Arquette
Release: 2024-12-28 16:41:10
Original
706 people have browsed it

How Can I Elegantly Format Floating-Point Numbers in Java Without Unnecessary Decimal Zeros?

Formatting Floating Numbers Elegantly without Extraneous Decimal Zeros

In the realm of Java programming, formatting floating-point numbers can present challenges, especially when dealing with a mix of integers stored as doubles and actual doubles. The default formatting method, String.format("%f"), often introduces trailing zeros for small values, distorting the desired output.

One solution is to employ a custom formatting method that distinguishes between integers and doubles. This can be achieved through conditional evaluation:

public static String fmt(double d) {
    if (d == (long) d)
        return String.format("%d", (long) d);
    else
        return String.format("%s", d);
}
Copy after login

This method returns integers as integers and doubles with the minimum necessary precision, yielding the desired output:

232
0.18
1237875192
4.58
0
1.2345
Copy after login

By utilizing conditional formatting, this approach avoids performance penalties associated with string manipulation and ensures accurate representation of both integer and double values.

Caution: Note that string formatting in Java can be locale-dependent, so the provided solution may need to be adjusted accordingly based on the locale settings of your application.

The above is the detailed content of How Can I Elegantly Format Floating-Point Numbers in Java Without Unnecessary Decimal Zeros?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template