[英]Formatting 0 to include decimal places using DecimalFormat
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class HelloWorld{
public static void main(String []args){
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("two decimals: " + new BigDecimal(df.format(123.435435))) ;
System.out.println("zero two decimal places: " + new BigDecimal(df.format(0.0000))) ;
System.out.println("zero without a decimal place: " + new BigDecimal(df.format(0))) ;
}
}
输出是:
three decimals: 123.44
zero two decimal places: 0
zero without a decimal place: 0
现在, DecimalFormat df = new DecimalFormat("#.##");
这是在我的应用程序中广泛使用的东西,我还没有修改它的选项。 如何在上述程序中将 0 打印为 0.00?
根据Javadoc格式,'#' 将显示零作为不存在。 您可以使用“0”来无条件地显示小数位,即使相关数字为零。
请注意,BigDecimals 用于需要高精度的计算,例如金融应用程序。 如果您只需要打印格式化的数字,那么您实际上并不需要它们。
DecimalFormat df = new DecimalFormat("#.##");
DecimalFormat dfWithZeroes = new DecimalFormat("0.00");
System.out.println("two decimals: " + df.format(123.435435));
System.out.println("zero two decimals: " + dfWithZeroes.format(0.0000));
System.out.println("zero without a decimal: " + df.format(0));
使用 BigDecimals:
System.out.println("two decimals: " + new BigDecimal(df.format(123.435435)));
System.out.println("zero two decimals: " + new BigDecimal(dfWithZeroes.format(0.0000)));
System.out.println("zero without a decimal: " + new BigDecimal(df.format(0)));
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class HelloWorld{
public static void main(String []args){
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("");
System.out.println("------------Handling zero with Decimal Formatter API------------");
System.out.println("");
DecimalFormat dfWithZeroes = new DecimalFormat("0.0");
System.out.println("two decimals: " + df.format(123.435435));
System.out.println("zero two decimals: " + dfWithZeroes.format(0));
System.out.println("zero without a decimal: " + df.format(0));
System.out.println("");
System.out.println("------------Handling zero with BigDecimal API------------");
System.out.println("");
BigDecimal zero = BigDecimal.ZERO;
System.out.println("Zero without scaling " + zero);
System.out.println("Zero with scale 1: " + zero.setScale(1));
System.out.println("Zero with scale 2: " + zero.setScale(2));
System.out.println("Zero with scale 3: " + zero.setScale(3));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.