删除Java中的尾随零 [英] Remove trailing zero in Java

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

问题描述

我有字符串(来自DB),它可能包含数值。如果它包含数值,我想删除尾随零,例如:

I have Strings (from DB), which may contain numeric values. If it contains numeric values, I'd like to remove trailing zeros such as:


  • 10.0000


  • 10.234000

  • 10.0000
  • 10.234000

str.replaceAll(\\\\ * *,),适用于第一个,但不适用于第二个。

str.replaceAll("\\.0*$", ""), works on the first one, but not the second one.

许多答案指向使用 BigDecimal ,但字符串我得到的可能不是数字。所以我认为更好的解决方案可能是通过正则表达式。

A lot of the answers point to use BigDecimal, but the String I get may not be numeric. So I think a better solution probably is through the Regex.

推荐答案

有可能:

1000    -> 1000
10.000  -> 10 (without point in result)
10.0100 -> 10.01 
10.1234 -> 10.1234

我是懒惰和愚蠢的,只是

I am lazy and stupid, just

s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");

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

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