如何很好地格式化浮动数字字符串没有不必要的小数0's

64位double可以精确地表示整数+/- 253

鉴于这一事实,我选择使用双类型作为我所有类型的单一类型,因为我的最大整数是一个无符号的32位数字。

但现在我必须打印这些伪整数,但问题是它们也和实际的双精度数混合在一起。

那么如何在Java中很好地打印这些double呢?

我尝试了String.format("%f", value),它很接近,除了对于小值我得到了很多尾随零。

下面是%f的输出示例

232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000

我想要的是:

232
0.18
1237875192
4.58
0
1.2345

当然,我可以写一个函数来修剪这些零,但由于字符串操作,这是大量的性能损失。我能用其他格式的代码做得更好吗?


Tom E.和Jeremy S.的答案是不可接受的,因为他们都任意舍入到小数点后两位。请先理解问题再回答。


请注意,String.format(format, args...)< >强依赖< / >强(见下面的答案)。

790293 次浏览

不,没关系。由于字符串操作造成的性能损失为零。

下面是修剪%f后末端的代码:

private static String trimTrailingZeros(String number) {
if(!number.contains(".")) {
return number;
}


return number.replaceAll("\\.?0*$", "");
}
String.format("%.2f", value);
String s = "1.210000";
while (s.endsWith("0")){
s = (s.substring(0, s.length() - 1));
}

这将使字符串丢弃0-s尾。

最好的方法如下:

public class Test {


public static void main(String args[]){
System.out.println(String.format("%s something", new Double(3.456)));
System.out.println(String.format("%s something", new Double(3.456234523452)));
System.out.println(String.format("%s something", new Double(3.45)));
System.out.println(String.format("%s something", new Double(3)));
}
}

输出:

3.456 something
3.456234523452 something
3.45 something
3.0 something

唯一的问题是最后一个。0没有被删除。但如果你能接受这一点,那么这种方法就最好了。%。2f会四舍五入到小数点后两位。DecimalFormat也是如此。如果你需要所有的小数点后数位,但不需要后面的零,那么这个方法是最好的。

我做了一个DoubleFormatter来有效地转换大量的双精度值到一个漂亮/像样的字符串:

double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4, 6); // 4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
  • 如果V的整数部分大于MaxInteger =>以科学格式(1.2345E+30)显示V。否则,以正常格式(124.45678)显示。
  • MaxDecimal决定十进制数(用银行家的舍入修饰)

代码如下:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;


import com.google.common.base.Preconditions;
import com.google.common.base.Strings;


/**
* Convert a double to a beautiful String (US-local):
*
* double horribleNumber = 3598945.141658554548844;
* DoubleFormatter df = new DoubleFormatter(4,6);
* String beautyDisplay = df.format(horribleNumber);
* String beautyLabel = df.formatHtml(horribleNumber);
*
* Manipulate 3 instances of NumberFormat to efficiently format a great number of double values.
* (avoid to create an object NumberFormat each call of format()).
*
* 3 instances of NumberFormat will be reused to format a value v:
*
* if v < EXP_DOWN, uses nfBelow
* if EXP_DOWN <= v <= EXP_UP, uses nfNormal
* if EXP_UP < v, uses nfAbove
*
* nfBelow, nfNormal and nfAbove will be generated base on the precision_ parameter.
*
* @author: DUONG Phu-Hiep
*/
public class DoubleFormatter
{
private static final double EXP_DOWN = 1.e-3;
private double EXP_UP; // always = 10^maxInteger
private int maxInteger_;
private int maxFraction_;
private NumberFormat nfBelow_;
private NumberFormat nfNormal_;
private NumberFormat nfAbove_;


private enum NumberFormatKind {Below, Normal, Above}


public DoubleFormatter(int maxInteger, int maxFraction){
setPrecision(maxInteger, maxFraction);
}


public void setPrecision(int maxInteger, int maxFraction){
Preconditions.checkArgument(maxFraction>=0);
Preconditions.checkArgument(maxInteger>0 && maxInteger<17);


if (maxFraction == maxFraction_ && maxInteger_ == maxInteger) {
return;
}


maxFraction_ = maxFraction;
maxInteger_ = maxInteger;
EXP_UP =  Math.pow(10, maxInteger);
nfBelow_ = createNumberFormat(NumberFormatKind.Below);
nfNormal_ = createNumberFormat(NumberFormatKind.Normal);
nfAbove_ = createNumberFormat(NumberFormatKind.Above);
}


private NumberFormat createNumberFormat(NumberFormatKind kind) {


// If you do not use the Guava library, replace it with createSharp(precision);
final String sharpByPrecision = Strings.repeat("#", maxFraction_);


NumberFormat f = NumberFormat.getInstance(Locale.US);


// Apply bankers' rounding:  this is the rounding mode that
// statistically minimizes cumulative error when applied
// repeatedly over a sequence of calculations
f.setRoundingMode(RoundingMode.HALF_EVEN);


if (f instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) f;
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();


// Set group separator to space instead of comma


//dfs.setGroupingSeparator(' ');


// Set Exponent symbol to minus 'e' instead of 'E'
if (kind == NumberFormatKind.Above) {
dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
} else {
dfs.setExponentSeparator("e");
}


df.setDecimalFormatSymbols(dfs);


// Use exponent format if v is outside of [EXP_DOWN,EXP_UP]


if (kind == NumberFormatKind.Normal) {
if (maxFraction_ == 0) {
df.applyPattern("#,##0");
} else {
df.applyPattern("#,##0."+sharpByPrecision);
}
} else {
if (maxFraction_ == 0) {
df.applyPattern("0E0");
} else {
df.applyPattern("0."+sharpByPrecision+"E0");
}
}
}
return f;
}


public String format(double v) {
if (Double.isNaN(v)) {
return "-";
}
if (v==0) {
return "0";
}
final double absv = Math.abs(v);


if (absv<EXP_DOWN) {
return nfBelow_.format(v);
}


if (absv>EXP_UP) {
return nfAbove_.format(v);
}


return nfNormal_.format(v);
}


/**
* Format and higlight the important part (integer part & exponent part)
*/
public String formatHtml(double v) {
if (Double.isNaN(v)) {
return "-";
}
return htmlize(format(v));
}


/**
* This is the base alogrithm: create a instance of NumberFormat for the value, then format it. It should
* not be used to format a great numbers of value
*
* We will never use this methode, it is here only to understanding the Algo principal:
*
* format v to string. precision_ is numbers of digits after decimal.
* if EXP_DOWN <= abs(v) <= EXP_UP, display the normal format: 124.45678
* otherwise display scientist format with: 1.2345e+30
*
* pre-condition: precision >= 1
*/
@Deprecated
public String formatInefficient(double v) {


// If you do not use Guava library, replace with createSharp(precision);
final String sharpByPrecision = Strings.repeat("#", maxFraction_);


final double absv = Math.abs(v);


NumberFormat f = NumberFormat.getInstance(Locale.US);


// Apply bankers' rounding:  this is the rounding mode that
// statistically minimizes cumulative error when applied
// repeatedly over a sequence of calculations
f.setRoundingMode(RoundingMode.HALF_EVEN);


if (f instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) f;
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();


// Set group separator to space instead of comma


dfs.setGroupingSeparator(' ');


// Set Exponent symbol to minus 'e' instead of 'E'


if (absv>EXP_UP) {
dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
} else {
dfs.setExponentSeparator("e");
}
df.setDecimalFormatSymbols(dfs);


//use exponent format if v is out side of [EXP_DOWN,EXP_UP]


if (absv<EXP_DOWN || absv>EXP_UP) {
df.applyPattern("0."+sharpByPrecision+"E0");
} else {
df.applyPattern("#,##0."+sharpByPrecision);
}
}
return f.format(v);
}


/**
* Convert "3.1416e+12" to "<b>3</b>.1416e<b>+12</b>"
* It is a html format of a number which highlight the integer and exponent part
*/
private static String htmlize(String s) {
StringBuilder resu = new StringBuilder("<b>");
int p1 = s.indexOf('.');


if (p1>0) {
resu.append(s.substring(0, p1));
resu.append("</b>");
} else {
p1 = 0;
}


int p2 = s.lastIndexOf('e');
if (p2>0) {
resu.append(s.substring(p1, p2));
resu.append("<b>");
resu.append(s.substring(p2, s.length()));
resu.append("</b>");
} else {
resu.append(s.substring(p1, s.length()));
if (p1==0){
resu.append("</b>");
}
}
return resu.toString();
}
}

注意:我使用了番石榴库中的两个函数。如果你不使用Guava,你可以自己编码:

/**
* Equivalent to Strings.repeat("#", n) of the Guava library:
*/
private static String createSharp(int n) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++) {
sb.append('#');
}
return sb.toString();
}

如果这个想法是将存储为双精度的整数打印出来,就像它们是整数一样,否则以最小的必要精度打印双精度:

public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}

生产:

232
0.18
1237875192
4.58
0
1.2345

并且不依赖于字符串操作。

String s = String.valueof("your int variable");
while (g.endsWith("0") && g.contains(".")) {
g = g.substring(0, g.length() - 1);
if (g.endsWith("."))
{
g = g.substring(0, g.length() - 1);
}
}

这里有两种方法来实现它。首先,更短(可能更好)的方式:

public static String formatFloatToString(final float f)
{
final int i = (int)f;
if(f == i)
return Integer.toString(i);
return Float.toString(f);
}

这里有一个更长的,可能更糟糕的方法:

public static String formatFloatToString(final float f)
{
final String s = Float.toString(f);
int dotPos = -1;
for(int i=0; i<s.length(); ++i)
if(s.charAt(i) == '.')
{
dotPos = i;
break;
}


if(dotPos == -1)
return s;


int end = dotPos;
for(int i = dotPos + 1; i<s.length(); ++i)
{
final char c = s.charAt(i);
if(c != '0')
end = i + 1;
}
final String result = s.substring(0, end);
return result;
}

这里有一个实际有效的答案(这里不同答案的组合)

public static String removeTrailingZeros(double f)
{
if(f == (int)f) {
return String.format("%d", (int)f);
}
return String.format("%f", f).replaceAll("0*$", "");
}

在我的机器上,下面的函数大约比JasonD的回答提供的函数快7倍,因为它避免了String.format:

public static String prettyPrint(double d) {
int i = (int) d;
return d == i ? String.valueOf(i) : String.valueOf(d);
}

简而言之:

如果你想摆脱后面的0和语言环境问题,那么你应该使用:

double myValue = 0.00000021d;


DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS


System.out.println(df.format(myValue)); //output: 0.00000021

解释:

为什么其他答案不适合我:

  • Double.toString()System.out.printlnFloatingDecimal.toJavaFormatString使用科学符号,如果double小于10^ 3或大于或等于10^7

     double myValue = 0.00000021d;
    String.format("%s", myvalue); //output: 2.1E-7
    
  • 通过使用%f,默认的十进制精度是6,否则你可以硬编码它,但如果你有更少的小数,它会导致额外的0添加。例子:

     double myValue = 0.00000021d;
    String.format("%.12f", myvalue); // Output: 0.000000210000
    
  • 通过使用setMaximumFractionDigits(0);%.0f可以删除任何十进制精度,这对于整数/长整数是可以的,但对于双精度则不行

     double myValue = 0.00000021d;
    System.out.println(String.format("%.0f", myvalue)); // Output: 0
    DecimalFormat df = new DecimalFormat("0");
    System.out.println(df.format(myValue)); // Output: 0
    
  • 使用DecimalFormat,你是本地依赖的。在法语区域设置中,小数点分隔符是逗号,而不是点:

     double myValue = 0.00000021d;
    DecimalFormat df = new DecimalFormat("0");
    df.setMaximumFractionDigits(340);
    System.out.println(df.format(myvalue)); // Output: 0,00000021
    

    使用ENGLISH区域设置可以确保在程序运行的任何地方获得一个小数点分隔符点。

为什么使用340那么setMaximumFractionDigits?

两个原因:

  • setMaximumFractionDigits接受一个整数,但是它的实现允许的最大数字是DecimalFormat.DOUBLE_FRACTION_DIGITS,等于340
  • Double.MIN_VALUE = 4.9E-324,所以有340个数字,你肯定不会四舍五入的双精度损失

使用:

if (d % 1.0 != 0)
return String.format("%s", d);
else
return String.format("%.0f", d);

这应该与Double支持的极值一起工作。它的收益率:

0.12
12
12.144252
0

请注意,String.format(format, args...)< em >依赖< / em >,因为它格式化了使用用户的默认语言环境,,也就是说,可能在里面有逗号甚至空格,如123 456789123456年.789,这可能不是你所期望的。

您可能更喜欢使用String.format((Locale)null, format, args...)

例如,

    double f = 123456.789d;
System.out.println(String.format(Locale.FRANCE,"%f",f));
System.out.println(String.format(Locale.GERMANY,"%f",f));
System.out.println(String.format(Locale.US,"%f",f));

打印

123456,789000
123456,789000
123456.789000

String.format(format, args...)在不同国家也会这样做。

EDIT好的,既然已经讨论了有关手续的问题:

    res += stripFpZeroes(String.format((Locale) null, (nDigits!=0 ? "%."+nDigits+"f" : "%f"), value));
...


protected static String stripFpZeroes(String fpnumber) {
int n = fpnumber.indexOf('.');
if (n == -1) {
return fpnumber;
}
if (n < 2) {
n = 2;
}
String s = fpnumber;
while (s.length() > n && s.endsWith("0")) {
s = s.substring(0, s.length()-1);
}
return s;
}

你说你选择存储你的数字与双类型。我认为这可能是问题的根源,因为它迫使您将整数存储为双精度(因此丢失了关于值性质的初始信息)。将数字存储在数量类(Double和Integer的超类)的实例中并依赖多态性来确定每个数字的正确格式如何?

我知道重构整个代码可能是不可接受的,但它可以在不需要额外的代码/强制转换/解析的情况下产生所需的输出。

例子:

import java.util.ArrayList;
import java.util.List;


public class UseMixedNumbers {


public static void main(String[] args) {
List<Number> listNumbers = new ArrayList<Number>();


listNumbers.add(232);
listNumbers.add(0.18);
listNumbers.add(1237875192);
listNumbers.add(4.58);
listNumbers.add(0);
listNumbers.add(1.2345);


for (Number number : listNumbers) {
System.out.println(number);
}
}


}

将产生以下输出:

232
0.18
1237875192
4.58
0
1.2345
if (d == Math.floor(d)) {
return String.format("%.0f", d); //Format is: 0 places after decimal point
} else {
return Double.toString(d);
}

更多信息:https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

我的观点是:

if(n % 1 == 0) {
return String.format(Locale.US, "%.0f", n));
} else {
return String.format(Locale.US, "%.1f", n));
}

下面这个可以很好地完成工作:

    public static String removeZero(double number) {
DecimalFormat format = new DecimalFormat("#.###########");
return format.format(number);
}
new DecimalFormat("00.#").format(20.236)
//out =20.2


new DecimalFormat("00.#").format(2.236)
//out =02.2
  1. 0表示最小位数
  2. 渲染#数字
public static String fmt(double d) {
String val = Double.toString(d);
String[] valArray = val.split("\\.");
long valLong = 0;
if(valArray.length == 2) {
valLong = Long.parseLong(valArray[1]);
}
if (valLong == 0)
return String.format("%d", (long) d);
else
return String.format("%s", d);
}

我不得不使用这个,因为d == (long)dSonarQube报告中给了我违例。

使用DecimalFormatsetMinimumFractionDigits(0)

这是我想到的:

  private static String format(final double dbl) {
return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);
}

它是一个简单的一行程序,仅在确实需要时才强制转换为int类型。

用分组、四舍五入和没有不必要的零(双位数)格式化价格。

规则:

  1. 结尾没有零(2.0000 = 2; 1.0100000 = 1.01)
  2. 点后最多两位数(2.010 = 2.01; 0.20 = 0.2)
  3. 点后的第二位数字(1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0)的四舍五入
  4. 返回0 (null/-0 = 0)
  5. 添加$ (= $56/-$56)
  6. 分组(# EYZ0)

更多的例子:

# EYZ0

# EYZ0

# EYZ0

# EYZ0

它是用芬兰湾的科特林编写的,作为Double的一个有趣的扩展(因为它在Android中使用),但它可以很容易地转换为Java,因为使用了Java类。

/**
* 23.0 -> $23
*
* 23.1 -> $23.1
*
* 23.01 -> $23.01
*
* 23.99 -> $23.99
*
* 23.999 -> $24
*
* -0.0 -> $0
*
* -5.00 -> -$5
*
* -5.019 -> -$5.02
*/
fun Double?.formatUserAsSum(): String {
return when {
this == null || this == 0.0 -> "$0"
this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
}
}

使用方法:

var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20


yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0

# EYZ0: # EYZ1

对于Kotlin,你可以使用这样的扩展:

fun Double.toPrettyString() =
if(this - this.toLong() == 0.0)
String.format("%d", this.toLong())
else
String.format("%s", this)
float price = 4.30;
DecimalFormat format = new DecimalFormat("0.##"); // Choose the number of decimal places to work with in case they are different than zero and zero value will be removed
format.setRoundingMode(RoundingMode.DOWN); // Choose your Rounding Mode
System.out.println(format.format(price));

以下是一些测试的结果:

4.30     => 4.3
4.39     => 4.39  // Choose format.setRoundingMode(RoundingMode.UP) to get 4.4
4.000000 => 4
4        => 4

这是另一个答案,它有一个选项来附加小数只有在小数不是零。

   /**
* Example: (isDecimalRequired = true)
* d = 12345
* returns 12,345.00
*
* d = 12345.12345
* returns 12,345.12
*
* ==================================================
* Example: (isDecimalRequired = false)
* d = 12345
* returns 12,345 (notice that there's no decimal since it's zero)
*
* d = 12345.12345
* returns 12,345.12
*
* @param d float to format
* @param zeroCount number decimal places
* @param isDecimalRequired true if it will put decimal even zero,
* false will remove the last decimal(s) if zero.
*/
fun formatDecimal(d: Float? = 0f, zeroCount: Int, isDecimalRequired: Boolean = true): String {
val zeros = StringBuilder()


for (i in 0 until zeroCount) {
zeros.append("0")
}


var pattern = "#,##0"


if (zeros.isNotEmpty()) {
pattern += ".$zeros"
}


val numberFormat = DecimalFormat(pattern)


var formattedNumber = if (d != null) numberFormat.format(d) else "0"


if (!isDecimalRequired) {
for (i in formattedNumber.length downTo formattedNumber.length - zeroCount) {
val number = formattedNumber[i - 1]


if (number == '0' || number == '.') {
formattedNumber = formattedNumber.substring(0, formattedNumber.length - 1)
} else {
break
}
}
}


return formattedNumber
}

JSF应用程序中,我使用它来格式化数字而不带尾零。最初的内置格式化程序要求您指定小数位数的最大数量,如果您有太多小数位数,这在这里也很有用。

/**
* Formats the given Number as with as many fractional digits as precision
* available.<br>
* This is a convenient method in case all fractional digits shall be
* rendered and no custom format / pattern needs to be provided.<br>
* <br>
* This serves as a workaround for {@link NumberFormat#getNumberInstance()}
* which by default only renders up to three fractional digits.
*
* @param number
* @param locale
* @param groupingUsed <code>true</code> if grouping shall be used
*
* @return
*/
public static String formatNumberFraction(final Number number, final Locale locale, final boolean groupingUsed)
{
if (number == null)
return null;


final BigDecimal bDNumber = MathUtils.getBigDecimal(number);


final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
numberFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale()));
numberFormat.setGroupingUsed(groupingUsed);


// Convert back for locale percent formatter
return numberFormat.format(bDNumber);
}


/**
* Formats the given Number as percent with as many fractional digits as
* precision available.<br>
* This is a convenient method in case all fractional digits shall be
* rendered and no custom format / pattern needs to be provided.<br>
* <br>
* This serves as a workaround for {@link NumberFormat#getPercentInstance()}
* which does not renders fractional digits.
*
* @param number Number in range of [0-1]
* @param locale
*
* @return
*/
public static String formatPercentFraction(final Number number, final Locale locale)
{
if (number == null)
return null;


final BigDecimal bDNumber = MathUtils.getBigDecimal(number).multiply(new BigDecimal(100));


final NumberFormat percentScaleFormat = NumberFormat.getPercentInstance(locale);
percentScaleFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale() - 2));


final BigDecimal bDNumberPercent = bDNumber.multiply(new BigDecimal(0.01));


// Convert back for locale percent formatter
final String strPercent = percentScaleFormat.format(bDNumberPercent);


return strPercent;
}

考虑locale的简单解决方案:

double d = 123.45;
NumberFormat numberFormat = NumberFormat.getInstance(Locale.GERMANY);
System.out.println(numberFormat.format(d));

由于在德国使用逗号作为小数分隔符,因此上面将打印:

123年,45

使用给定的十进制长度…

public static String getLocaleFloatValueDecimalWithLength(Locale loc, float value, int length) {
//make string from float value
return String.format(loc, (value % 1 == 0 ? "%.0f" : "%."+length+"f"), value);
}