Home > Java > javaTutorial > How to output two decimal places in java

How to output two decimal places in java

下次还敢
Release: 2024-05-07 03:48:16
Original
1018 people have browsed it

To output two decimal places in Java, you can use the DecimalFormat class and implement the following steps: Create a DecimalFormat object and specify a format that retains two decimal places. Use DecimalFormat to format numbers. Print the formatted number.

How to output two decimal places in java

How to output two decimal places in Java

To output two decimal places in Java, you can use DecimalFormat Class. DecimalFormat Allows you to customize the format of the decimal point, including the number of digits after the decimal point.

Here are the steps on how to output two decimal places in Java:

  1. Create a DecimalFormat object

    <code class="java">DecimalFormat df = new DecimalFormat("#.##");</code>
    Copy after login

    where "#.##" represents the format of two decimal places.

  2. Use DecimalFormat to format numbers

    <code class="java">String formattedNumber = df.format(123.456);</code>
    Copy after login

    This will format 123.456 to "123.46", retain two decimal places.

  3. Print the formatted number

    <code class="java">System.out.println(formattedNumber);</code>
    Copy after login

Output:

<code>123.46</code>
Copy after login

Example Code:

<code class="java">import java.text.DecimalFormat;

public class DecimalFormatExample {

    public static void main(String[] args) {
        // 创建一个 DecimalFormat 对象,保留小数点后两位
        DecimalFormat df = new DecimalFormat("#.##");

        // 格式化一个数字
        String formattedNumber = df.format(123.456);

        // 打印格式化后的数字
        System.out.println(formattedNumber);
    }
}</code>
Copy after login

The above is the detailed content of How to output two decimal places in java. 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