简体   繁体   English

如何摆脱小数点前小于零的小数点前的零?

[英]How to get rid of leading zero before the decimal point in a double less than one?

I am doing a rather large project (for me, is an AP JAVA course in high school). 我正在做一个相当大的项目(对我来说,这是高中的AP JAVA课程)。 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 例如:.4999轮---> 0.5我需要:.4999轮---> .5

Thanks in advance 提前致谢

As Ingo mentioned, you'll need to get a String representation of the number in order to modify the output as desired. 如Ingo所述,您需要获取数字的String表示形式,以便根据需要修改输出。 One solution would be to use java.text.NumberFormat . 一种解决方案是使用java.text.NumberFormat setMinimumIntegerDigits(0) seems to fit the bill. setMinimumIntegerDigits(0)似乎很合适。 I'm sure there are plenty more options as well. 我相信还有更多选择。

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

Working Fiddle 工作小提琴

The DecimalFormat class can be used. 可以使用DecimalFormat类。

DecimalFormat df = new DecimalFormat("####0.0");
System.out.println("Value: " + df.format(value));

May seem weird to you, but you can use regex to strip off the leading zero like this: 对您来说可能看起来很奇怪,但是您可以使用regex去除前导零,如下所示:

(assuming that you already know how to round the decimal place to one) (假设您已经知道如何将小数点后一位舍入)

        double value = 0.5;

        String val = Double.toString( value ).replaceAll( "^0(\\..*)$", "$1" );

        System.out.println( val );

Console: 安慰:

       .5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM