安全字符串到 BigDecimal 转换
我正在尝试从字符串中读取一些 BigDecimal 值。假设我有这个字符串:“1,000,000,000.999999999999999”,我想从中得到一个 BigDecimal 。有什么方法可以做到呢?
首先,我不喜欢使用字符串替换(替换逗号等)的解决方案。我认为应该有一些简洁的格式化程序来为我完成这项工作。
我找到了一个 DecimalFormatter 类,但是当它通过 double 操作时,会丢失大量精度。
那么,我该怎么做呢?
I'm trying to read some BigDecimal values from the string. Let's say I have this String: "1,000,000,000.999999999999999" and I want to get a BigDecimal out of it. What is the way to do it?
First of all, I don't like the solutions using string replaces (replacing commas etc.). I think there should be some neat formatter to do that job for me.
I've found a DecimalFormatter class, however as it operates through double - huge amounts of precision are lost.
So, how can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
查看
setParseBigDecimal
(十进制格式)。使用此设置器,
parse
将为您返回一个 BigDecimal。Check out
setParseBigDecimal
in DecimalFormat. With this setter,parse
will return a BigDecimal for you.完整代码证明没有
NumberFormatException
被抛出:输出
Full code to prove that no
NumberFormatException
is thrown:Output
以下示例代码运行良好(需要动态获取语言环境)
The following sample code works well (locale need to be obtained dynamically)
代码可以更简洁,但这似乎可以针对不同的区域设置。
The code could be cleaner, but this seems to do the trick for different locales.
我需要一个解决方案,在不知道区域设置且与区域设置无关的情况下将 String 转换为 BigDecimal。我找不到这个问题的任何标准解决方案,所以我编写了自己的辅助方法。也许它也对其他人有帮助:
更新:警告!此辅助方法仅适用于十进制数,因此数字始终有小数点!否则,辅助方法可能会为 1000 到 999999(正/负)之间的数字提供错误的结果。感谢bezmax的出色贡献!
当然我已经测试过该方法:
I needed a solution to convert a String to a BigDecimal without knowing the locale and being locale-independent. I couldn't find any standard solution for this problem so i wrote my own helper method. May be it helps anybody else too:
Update: Warning! This helper method works only for decimal numbers, so numbers which always have a decimal point! Otherwise the helper method could deliver a wrong result for numbers between 1000 and 999999 (plus/minus). Thanks to bezmax for his great input!
Of course i've tested the method:
下面是我的做法:
显然,如果这在生产代码中进行,事情就不会那么简单。
我认为简单地从字符串中删除逗号没有问题。
Here is how I would do it:
Obviously, if this were going in production code, it wouldn't be that simple.
I see no issue with simply removing the commas from the String.
将从字符串中删除除数字和点之外的所有字符。
为了使其能够识别区域设置,您可能需要使用
getDecimalSeparator()
来自java.text.DecimalFormatSymbols
。我不懂Java,但它可能看起来像这样:will remove all characters except digits and the dot from your string.
To make it locale-aware, you might want to use
getDecimalSeparator()
fromjava.text.DecimalFormatSymbols
. I don't know Java, but it might look like this:老话题,但也许最简单的是使用 Apache commons NumberUtils,它有一个方法 createBigDecimal (String value)....
我想(希望)它会考虑区域设置,否则它将毫无用处。
Old topic but maybe the easiest is to use Apache commons NumberUtils which has a method createBigDecimal (String value)....
I guess (hope) it takes locales into account or else it would be rather useless.
请尝试这对我有用
Please try this its working for me