我可以用system。out。print吗?
当前回答
试试这个:
private static String getDecimalFormat(double value) {
String getValue = String.valueOf(value).split("[.]")[1];
if (getValue.length() == 1) {
return String.valueOf(value).split("[.]")[0] +
"."+ getValue.substring(0, 1) +
String.format("%0"+1+"d", 0);
} else {
return String.valueOf(value).split("[.]")[0]
+"." + getValue.substring(0, 2);
}
}
其他回答
只需执行String str = System.out.printf("%。2 f”,val)。取代 (",", ".");如果你想确保独立于用户的Locale,你将总是得到/显示一个"."作为小数分隔符。这是必须的,如果你不想让你的程序崩溃,如果你以后做一些转换,如float f = float . parsefloat (str);
试试这个:
private static String getDecimalFormat(double value) {
String getValue = String.valueOf(value).split("[.]")[1];
if (getValue.length() == 1) {
return String.valueOf(value).split("[.]")[0] +
"."+ getValue.substring(0, 1) +
String.format("%0"+1+"d", 0);
} else {
return String.valueOf(value).split("[.]")[0]
+"." + getValue.substring(0, 2);
}
}
public String getDecimalNumber(String number) {
Double d=Double.parseDouble(number);
return String.format("%.5f", d);
}
还要注意NumberFormatException
看看DecimalFormat
下面是教程中的一个例子:
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
如果你选择像“###”这样的图案。##”,你会得到两位小数点后,我认为值是四舍五入。你会想要查看链接以获得你想要的确切格式(例如,你是否想要后面的零)
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
推荐文章
- 在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中引用环境变量?