我可以用system。out。print吗?
当前回答
看看DecimalFormat
下面是教程中的一个例子:
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
如果你选择像“###”这样的图案。##”,你会得到两位小数点后,我认为值是四舍五入。你会想要查看链接以获得你想要的确切格式(例如,你是否想要后面的零)
其他回答
float f = 102.236569f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
用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)
public String getDecimalNumber(String number) {
Double d=Double.parseDouble(number);
return String.format("%.5f", d);
}
还要注意NumberFormatException
用于演示的简单小程序:
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);
}
}
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));
输出是22.35。 如果需要3个小数点,则将其更改为“%.3f”。
推荐文章
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 如何在POM.xml中引用环境变量?