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

How to output two decimal places in java

下次还敢
下次还敢Original
2024-05-07 03:48:16978browse

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>

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

  2. Use DecimalFormat to format numbers

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

    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>

Output:

<code>123.46</code>

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>

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!

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
Previous article:What does sc mean in javaNext article:What does sc mean in java