DecimalFormat和Double.valueOf() [英] DecimalFormat and Double.valueOf()

查看:228
本文介绍了DecimalFormat和Double.valueOf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的double值的十进制分隔符后删除不必要的符号。我是这样做的:

I'm trying to get rid of unnecessary symbols after decimal seperator of my double value. I'm doing it this way:

DecimalFormat format = new DecimalFormat("#.#####");
value = Double.valueOf(format.format(41251.50000000012343));

但是当我运行此代码时,它会抛出:

But when I run this code, it throws:

java.lang.NumberFormatException: For input string: "41251,5"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
    at java.lang.Double.valueOf(Double.java:447)
    at ...

正如我所见, Double.valueOf()适用于像11.1这样的字符串,但它会窒息在诸如11,1之类的字符串上。我该如何解决这个问题?是否有更优雅的方式,然后像

As I see, Double.valueOf() works great with strings like "11.1", but it chokes on strings like "11,1". How do I work around this? Is there a more elegant way then something like

Double.valueOf(format.format(41251.50000000012343).replaceAll(",", "."));

有没有办法覆盖 DecimalFormat的默认小数点分隔符上课?还有其他想法吗?

Is there a way to override the default decimal separator value of DecimalFormat class? Any other thoughts?

推荐答案


在我的双值的十进制分隔符之后删除不必要的符号

get rid of unnecessary symbols after decimal seperator of my double value

你实际上是否想要舍入到例如小数点后五位?然后只需使用

do you actually mean you want to round to e.g. the 5th decimal? Then just use

value = Math.round(value*1e5)/1e5;

(当然你也可以 Math.floor(价值* 1e5)/ 1e5 如果你真的想要切掉其他数字)

(of course you can also Math.floor(value*1e5)/1e5 if you really want the other digits cut off)

这篇关于DecimalFormat和Double.valueOf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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