如何摆脱小数点之前的小数点之前的前导零? [英] How to get rid of leading zero before the decimal point in a double less than one?
本文介绍了如何摆脱小数点之前的小数点之前的前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:.4999轮---> 0.5
我需要:.4999轮---> .5
提前致谢
解决方案
试试这个:
public static String format(double value,int decimalPlaces){
if(value> 1 || value< 0){
throw new IllegalArgumentException 值必须在0和1之间);
}
final String tmp = String.format(%。+ decimalPlaces +f,value);
return tmp.substring(tmp.indexOf('。'));
$ b <$>
System.out.println(format(0.4999d,1)); // .5
System.out.println(format(0.0299d,2)); // .03
System.out.println(format(0.34943d,3)); // .349
I am doing a rather large project (for me, is an AP JAVA course in high school). Anyways, for a portion of the project I need to be able to round a decimal and output it without the zero at the beginning before the decimal.
Ex: .4999 rounds ---> 0.5
I need: .4999 round ---> .5
Thanks in advance
解决方案 Try this:
public static String format(double value, int decimalPlaces) {
if (value >= 1 || value < 0) {
throw new IllegalArgumentException("Value must be between 0 and 1");
}
final String tmp = String.format("%." + decimalPlaces + "f", value);
return tmp.substring(tmp.indexOf('.'));
}
Examples:
System.out.println(format(0.4999d, 1)); // .5
System.out.println(format(0.0299d, 2)); // .03
System.out.println(format(0.34943d, 3)); // .349
这篇关于如何摆脱小数点之前的小数点之前的前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文