删除 BigDecimal 的前导零和分隔符
我们的应用程序可以获取以下数字:
0.1
0.02
0.003
等等。
这些值被我们的代码视为BigDecimal
,就我们使用货币进行操作而言。
Web UI 上有一个表单,用户应该在其中查看价格的这些浮动部分,转换为以下部分:
1
02
003
问题是,如何修剪输入中的前导 零
和 分隔符
价格。也许 BigDecimal
类有标准方法,如 trimLeadingZeroes(),但找不到任何标准方法。
更新: 仅修剪前导零和分隔符
例如:
1 is 0.1
27 is 0.27
Our application can get following numbers:
0.1
0.02
0.003
etc.
These values treated by our code as BigDecimal
,as far we operate with money.
There is form on web UI, where user should view these floating parts of prices, transformed to following ones:
1
02
003
The question is,how to trim leading zero
and delimiter character
in input prices. Perhaps BigDecimal
class has standard method something like trimLeadingZeroes(),but can't find any.
UPDATE:
trim just leading zero and delimiter symbol
For instance:
1 is 0.1
27 is 0.27
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
像这样的东西吗?
Something like this?
您是否尝试过调用
BigDecimal.unscaledValue
?缺点是 0.13 将是 13,而您可能想要 1.3...这有点难以判断。如果你能举出更多的例子,那真的会有帮助。(如果一开始的值是 1000,那么这种方法也会失败 - 你最终会得到 1...)
Have you tried calling
BigDecimal.unscaledValue
? The downside is that 0.13 would then be 13 whereas you possibly want 1.3... it's slightly hard to tell. If you could give more examples, that would really help.(That approach would also fail if the value were 1000 to start with - you'd end up with 1...)
是否可以像这样做一样简单:
所以如果你制作
它将打印
Could it be something as simple as doing this:
so if you make
It will print
当你必须处理分割某些东西时,最好使用字符串来完成它。
首先,您只需将 bigdecimal 转换为字符串
然后您只需将其拆分,
现在 String s2 包含分隔符后的数字
when ever you have to deal with splitting something its a good bet Strings can be used for it.
You first just convert the bigdecimal into a string
Then you simply split it as so
now String s2 contains the numbers after the delimiter
从
BigDecimal
到String
的转换:结果是:
该代码直接处理任何数字,并且仅考虑小数部分。
它还可以优雅地处理“0.0”。
这是您想要的转换吗?
Conversion from
BigDecimal
toString
:Results are:
The code works directly with any number and takes into account only the fractional part.
It also handles "0.0" gracefully.
Is this the conversion you wanted?
这是执行此操作的另一种简单方法 - 假设您的输入是 1.023456
这将给出您在 bd3 中查找的确切结果,即上面的示例中它将是 023456。
由于最后一行的条件,它对于整数也可以正常工作,即 1 将返回“”
Here is another simple way of doing this - assuming your input is 1.023456
This will give the exact result as you were looking for in bd3, i.e. it'll be 023456 for the above example.
It'll work ok for whole numbers too, due to the condition in last line, i.e. 1 will return ""
您可以使用
value
的字符串表示形式(BigDecimal
)和 StringUtils.substringAfter 执行此操作:You could use the string representation of
value
(aBigDecimal
) and StringUtils.substringAfter to do this:如何编写一个扩展方法来扩展此类型?简单的方法可能会将数字相乘直到> 1
How about writing an extension method to extend this type. Simple method might multiply number until > 1