public class Test { public static void main(String[] args) { String result= Test.roundByScale(2.00,2); System.out.println(result); } public static String roundByScale(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } if(scale == 0){ return new DecimalFormat("0").format(v); } String formatStr = "0."; for(int i=0;i<scale;i++){ formatStr = formatStr + "0"; } return new DecimalFormat(formatStr).format(v); } }
java保留小数点后几位,不足的用0补
最新推荐文章于 2024-11-21 16:41:59 发布
本文提供了一个Java程序示例,演示了如何使用DecimalFormat类来格式化小数,确保输出的小数位数符合指定的精度。此方法对于处理财务数据等需要精确到特定小数位的应用场景非常有用。
520

被折叠的 条评论
为什么被折叠?



