简体   繁体   English

Java DecimalFormat省略小数点前的前导零

[英]Java DecimalFormat to omit leading zero before decimal point

Let's take below code snippet 让我们看下面的代码片段

double f = .123;        
System.out.println(f);
System.out.println(new DecimalFormat(".###").format(f));

So we can use .### to omit the leading zero 0, though we have to define the trailing digits after decimal point/period. 因此,尽管我们必须定义小数点/句点后的尾数,但我们可以使用.###省略前导零0。

I want to define the DecimalFormat formatter that can serve unlimitted number of after-decimal-point digits. 我想定义DecimalFormat格式程序,该格式程序可以提供无限数量的after-decimal-point数字。

How can I do that? 我怎样才能做到这一点?

ps ps

I did try "." 我确实尝试过"." but that we print no decimal digits. 但是我们不打印十进制数字。 May we have some formation syntax like ".#*" ? 我们可以使用诸如".#*"类的格式语法吗?

Double is a finite approximation (64 bits including sign and exponent) so unlimited and exactness cannot be done with that. Double是有限近似值(包括正负号和指数在内的64位),因此无法做到无限和精确。

Use a BigDecimal. 使用BigDecimal。 A String constructor will take its precision by the string. String构造函数将根据字符串的精度。

BigDecimal n = new BigDecimal("0.1234567890123456789012345678901234567890");
n = n.multiply(n); // n now has double precision.
String s = n.toPlainString().replaceFirst("^0\\.", "."); // Without exponent.

As you want unlimited representation simply use toPlainString . 如要无限表示,只需使用toPlainString About dropping the zero before the period can be done a bit ugly with a regex replace. 通过使用正则表达式替换,在句点之前降低零可能很难做到。

You can turn the number to string and skip the first character: 您可以将数字转换为字符串,然后跳过第一个字符:

double f = .123;        
System.out.println(Double.toString(f).substring(1));

After a bit of researching, I don't believe that this can be achieved by using the DecimalFormat . 经过一些研究,我不相信可以通过使用DecimalFormat来实现。 However, ".#*" , that you suggest could be a useful addition. 但是,您建议使用".#*"作为有用的添加。

Since float has no unlimitted number of after-dicimal-points just use as many # as you expect at maximum. 由于float没有无限数量的after-dicimal-points ,因此最多使用您期望的#

You can also convert the number to a String and select a substring to display. 您也可以将数字转换为字符串,然后选择要显示的子字符串。

float f = 0.123;
String fs = Float.toString(f);
System.out.println(fs.substring(fs.indexOf('.'), fs.lenght());

This also works, if you don't know in advance, if you number has only one leading zero. 如果您事先不知道,如果您的数字只有一个前导零,这也可以使用。

Unfortunately I can not tell you if this is also possible with DecimalFormatter. 不幸的是,我不能告诉您DecimalFormatter是否也可以实现。

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

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