[英]Remove leading zeros with regex but keep minus-sign
I want to replace leading zeros in java with this expression found on this thread : 我想用这个线程上的表达式替换java中的前导零:
s.replaceFirst("^0+(?!$)", "")
But how can I make it work for values like -00.8899
? 但是我怎样才能让它适用于像
-00.8899
这样的值呢?
You can try with: 您可以尝试:
String output = "-00.8899".replace("^(-?)0*", "$1");
Output: 输出:
-.8899
Why are you dealing with a numeric value in a string variable? 为什么要处理字符串变量中的数值?
Java being a strongly-typed language, you would probably have an easier time converting that to a float or double, then doing all the business logic, then finally formatting the output. Java是一种强类型语言,您可能更容易将其转换为float或double,然后执行所有业务逻辑,最后格式化输出。
Something like: 就像是:
Double d = Double.parseDouble(s);
double val = d; //mind the auto-boxing/unboxing
//business logic
//get ready to display to the user
DecimalFormat df = new DecimalFormat("#.0000");
String s = df.format(d);
http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.