Java 如何在小数点前加0
我想在小数点之前加零,如果数字以小数点本身开始 输入:.2345 产出:0.2345 我使用的是Java 如何在小数点前加0,java,Java,我想在小数点之前加零,如果数字以小数点本身开始 输入:.2345 产出:0.2345 我使用的是decimalforamter。我避免使用字符串追加器 请建议 感谢您这将为您提供预期的输出: @Test public void testFloatLeadingZero(){ float value = .1221313F; DecimalFormat lFormatter = new DecimalFormat("##0.0000"); String lOutput = lForma
decimalforamter
。我避免使用字符串追加器
请建议
感谢您这将为您提供预期的输出:
@Test
public void testFloatLeadingZero(){
float value = .1221313F;
DecimalFormat lFormatter = new DecimalFormat("##0.0000");
String lOutput = lFormatter.format(value);
Assert.assertTrue(lOutput.startsWith("0."));
}
或使用String.format
:
@Test
public void testFloatLeadingZero(){
float value = .1221313F;
String lOutput = String.format("%.20f", value);
Assert.assertTrue(lOutput.startsWith("0."));
double value2 = .1221313d;
String lOutput2 = String.format("%.20d", value2);
Assert.assertTrue(lOutput2.startsWith("0."));
}
我想你用的是
Float
对吧?否则,您必须将f
替换为d
,以将Double
格式化为字符串。它在线程“main”java.lang.IllegalArgumentException中给出了异常:模式“%.4f%n”中的百分比/千分位字符太多
这种方法会限制小数点后的位数吗?因为如果它会那么抱歉,我将无法在我的情况下使用它,因为我需要保持原封不动。我想你需要在分隔符后4位数字。好的,那么我认为String.format更好。