在Java中加倍的值 [英] Double value to round up in Java

查看:107
本文介绍了在Java中加倍的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双重值= 1.068879335 我想对它进行四舍五入,只有两个十进制值,如1.07。

I have a double value = 1.068879335 i want to round it up with only two decimal values like 1.07.

我尝试这样

DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value);
double finalValue = Double.parseDouble(formate) ;

这是给我以下例外

java.lang.NumberFormatException: For input string: "1,07"
     at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
     at java.lang.Double.parseDouble(Double.java:510)

可以有人告诉我什么是错误的与我的代码。

can some one tell me what is wrong with my code.

finaly我需要finalValue = 1.07;

finaly i need the finalValue = 1.07;

推荐答案

请注意字符串中的逗号:1,07。 DecimalFormat 使用特定于语言环境的分隔符字符串,而 Double.parseDouble()不会。当你碰巧住在一个小数分隔符为,的国家/地区时,你无法解析你的号码。

Note the comma in your string: "1,07". DecimalFormat uses a locale-specific separator string, while Double.parseDouble() does not. As you happen to live in a country where the decimal separator is ",", you can't parse your number back.

但是,你可以使用相同的 DecimalFormat 来解析它:

However, you can use the same DecimalFormat to parse it back:

DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

但是您应该这样做:

double finalValue = Math.round( value * 100.0 ) / 100.0;

注意:如前所述,您只能使用浮点数如果您不需要精确控制精度。 (财务计算是使用它们的主要示例。)

Note: As has been pointed out, you should only use floating point if you don't need a precise control over accuracy. (Financial calculations being the main example of when not to use them.)

这篇关于在Java中加倍的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆