我可以用system。out。print吗?


当前回答

用于演示的简单小程序:

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);
    }
}

其他回答

你可以使用下面的快速代码,它在最后改变了自己。加上这个点后面有多少个0

float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");  
y1 = Float.valueOf(df.format(y1));

变量y1之前等于0.123456789。在代码之后,它只会变成0.12。

用str来浮动。

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));

  }
}

输出:

run:
[Original]: 0.09
[Local]: 0.10 
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)

下面是如何在Java中显示带有2位小数的浮点数据输出的代码:

float ratingValue = 52.98929821f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsFR = Float.valueOf(decimalFormat.format(ratingValue)); // output is 52.98

一个简单的技巧是生成一个更短的变量,将其与100相乘,四舍五入,然后再除以100.0。这样你就生成了一个小数点后2位的变量:

double new_variable = Math.round(old_variable*100) / 100.0;

这个“廉价的技巧”对我来说已经足够好了,并且适用于任何语言(我不是Java人,只是学习它)。

在Java中输出小数点后2位的浮点数:

    float f = (float)11/3;
    System.out.print(String.format("%.2f",f));

输出:3.67

>使用%。3f表示小数点后三位。