2011-12-01 60 views
4

我想改变浮动像这样:在Java中,如何删除float中的所有0?

10.5000 - > 10.5 10.0000 - > 10

如何删除所有零小数点后,并改变它要么浮动(如果有非-Zero)或int(如果只有零)?

在此先感谢。

+5

我不太明白。零点只是文本表示的产物,它们与浮点数如何在内部表示无关。你在寻找抑制尾随零的自定义输出格式吗? –

回答

10

为什么不尝试正则表达式?

new Float(10.25000f).toString().replaceAll("\\.?0*$", "") 
+0

这不太合理,因为'new Float(10.25000f).toString()'已经给你“10.25”,所以'.replaceAll(“0 * $”,“”)'是没有用的。 –

+1

'“\ .0 + $”'如果你想摆脱这段时间。 – Marcelo

+0

如果我将“0 * $”更改为“\ .0 + $”,它会显示“unexpected char:'。” - 我正在处理中。 – clerksx

1

根据需要为输出格式化数字。您不能删除内部的“0”值。

1

这两种不同的格式化处理它:

double d = 10.5F; 
DecimalFormat formatter = new DecimalFormat("0"); 
DecimalFormat decimalFormatter = new DecimalFormat("0.0"); 
String s; 
if (d % 1L > 0L) s = decimalFormatter.format(d); 
else s = formatter.format(d); 

System.out.println("s: " + s); 
1

java.math.BigDecimal有一个stripTrailingZeros()方法,它可以实现你要找的东西。

BigDecimal myDecimal = new BigDecimal(myValue); 
myDecimal.stripTrailingZeros(); 
myValue = myDecimal.floatValue(); 
16

嘛诀窍是,花车和双打自己真的没有尾随零本身;这只是它们打印(或初始化为文字)的方式,可能会显示它们。考虑这些例子:

Float.toString(10.5000); // => "10.5" 
Float.toString(10.0000); // => "10.0" 

可以使用DecimalFormat修复的“10.0”的例子:我有同样的问题

new java.text.DecimalFormat("#").format(10.0); // => "10" 
+1

这解释得更好。 +1。 –

+1

DecimalFormat的+1。另外使用半舍入的十进制格式。 http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html – HRgiger

+0

非常感谢。我没有说明我实际上在处理Processing。正则表达式更简单了我的情况。 – clerksx

0

,并找到在以下链接解决方法: StackOverFlow - How to nicely format floating numbers to string without unnecessary decimal 0

JasonD的回答是我所遵循的。这不是由地区决定的,这对我的问题很有帮助,并且没有长期价值的问题。

希望得到这个帮助。

添加内容从以上链接:

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 
+0

你可以从链接中添加一些内容吗? – Robert