How to display an output of float data with 2 deci

2019-01-01 09:02发布

Can I do it with System.out.print?

13条回答
明月照影归
2楼-- · 2019-01-01 09:14

Look at DecimalFormat

Here is an example from the tutorial:

  DecimalFormat myFormatter = new DecimalFormat(pattern);
  String output = myFormatter.format(value);
  System.out.println(value + "  " + pattern + "  " + output);

If you choose a pattern like "###.##", you will get two decimal places, and I think that the values are rounded up. You will want to look at the link to get the exact format you want (e.g., whether you want trailing zeros)

查看更多
余欢
3楼-- · 2019-01-01 09:15

small simple program for demonstration:

import java.io.*;
import java.util.Scanner;

public class twovalues {

    public static void main(String args[]) {

        float a,b;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Values For Calculation");

        a=sc.nextFloat();
        b=sc.nextFloat();

        float c=a/b;
        System.out.printf("%.2f",c);
    }
}
查看更多
零度萤火
4楼-- · 2019-01-01 09:18

You can use DecimalFormat. One way to use it:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));

Another one is to construct it using the #.## format.

I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.

查看更多
无色无味的生活
5楼-- · 2019-01-01 09:22

Many people have mentioned DecimalFormat. But you can also use printf if you have a recent version of Java:

System.out.printf("%1.2f", 3.14159D);

See the docs on the Formatter for more information about the printf format string.

查看更多
不再属于我。
6楼-- · 2019-01-01 09:23

OK - str to float.

package test;

import java.text.DecimalFormat;

public class TestPtz {
  public static void main(String[] args) {
    String preset0 = "0.09,0.20,0.09,0.07";
    String[] thisto = preset0.split(",");    
    float a = (Float.valueOf(thisto[0])).floatValue();
    System.out.println("[Original]: " + a);   
    a = (float) (a + 0.01);

    // Part 1 - for display / debug
    System.out.printf("[Local]: %.2f \n", a);
    // Part 2 - when value requires to be send as it is
    DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(2);
    System.out.println("[Remote]: " + df.format(a));

  }
}

Output:

run:
[Original]: 0.09
[Local]: 0.10 
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)
查看更多
深知你不懂我心
7楼-- · 2019-01-01 09:23

Below is code how you can display an output of float data with 2 decimal places in Java:

float ratingValue = 52.98929821f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsFR = Float.valueOf(decimalFormat.format(ratingValue)); // output is 52.98
查看更多
登录 后发表回答