Home >Java >javaTutorial >How to Precisely Format Floats in Java?

How to Precisely Format Floats in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 05:06:14755browse

How to Precisely Format Floats in Java?

How to Format Floats with Specific Precision in Java

Problem:
Need to print a float with precisely two decimal places.

Is System.out.print Sufficient?
No. System.out.print alone cannot format floats with specific precision.

Solution:

To achieve this formatting, utilize the printf method with the proper conversion specifier:

System.out.printf("%.2f", val);

Breakdown:

  • %: Start of the format specifier.
  • .: Separator between the whole and fractional parts.
  • 2: Number of decimal places to include.
  • f: Conversion character for a floating-point number.

Additional Conversion Characters:

Beyond floats, Java provides various conversion characters:

  • d: Decimal integer
  • o: Octal integer
  • e: Scientific notation

Example Usage:

To format and print a float named temperature with two decimal places:

System.out.printf("Temperature: %.2f degrees Celsius", temperature);

The above is the detailed content of How to Precisely Format Floats in Java?. 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