Java中如何显示无前置零的小数?棒球打击率格式问题求助
解决棒球打击率输出前置零的问题
嘿,我来帮你搞定这个问题!你遇到的核心问题出在把格式化后的字符串又转回了double类型——因为double是数值类型,当你把.345这样的格式化字符串转成double后,它会自动变回0.345的默认数值表示,打印时自然就带上了前置零。下面给你两种清晰的解决方案,顺便帮你修复代码里的一个小疏漏:
问题根源分析
你的getBattingAverage()方法里,先用DecimalFormat把打击率格式成了.000样式的字符串,但紧接着又用Double.parseDouble()把它转回了double。这一步完全没必要,反而破坏了格式化的结果,导致最终打印时出现前置零。
解决方案一:直接返回格式化后的字符串
修改getBattingAverage()的返回类型为String,直接返回格式化好的结果,避免数值类型的自动转换:
修改后的BaseballPlayer类方法
//BaseballPlayer parameters String name; int number; int singles; int doubles; int triples; int homeRuns; int atBats; int walks; int sacrificeFlies; //DecimalFormat static DecimalFormat df = new DecimalFormat(".000"); // 修复构造方法:补上doubles参数的赋值 public BaseballPlayer(String name, int number, int singles, int doubles, int triples, int homeRuns, int atBats, int walks, int sacrificeFlies) { this.name = name; this.number = number; this.singles = singles; this.doubles = doubles; // 新增:给doubles成员变量赋值 this.triples = triples; this.homeRuns = homeRuns; this.atBats = atBats; this.walks = walks; this.sacrificeFlies = sacrificeFlies; } public String getBattingAverage() { // 先计算打击率的原始数值 double average = (double) (singles + doubles + triples + homeRuns) / atBats; // 直接返回格式化后的字符串 return df.format(average); }
主类代码调用
BaseballPlayer player01 = new BaseballPlayer( "Mr. Business",13,12,XX,13,4,84,63,7); // 替换XX为实际的doubles数值 System.out.println(player01.getBattingAverage());
解决方案二:保持返回double,打印时再格式化
如果不想修改方法的返回类型,可以让getBattingAverage()直接返回原始数值,然后在主类中用DecimalFormat格式化输出:
修改后的BaseballPlayer类方法
public double getBattingAverage() { // 直接返回计算的原始数值,不再做格式化转double的操作 return (double) (singles + doubles + triples + homeRuns) / atBats; }
主类代码调用
BaseballPlayer player01 = new BaseballPlayer( "Mr. Business",13,12,XX,13,4,84,63,7); // 替换XX为实际的doubles数值 System.out.println(BaseballPlayer.df.format(player01.getBattingAverage()));
额外提醒:修复构造方法的疏漏
你原来的构造方法里没有给doubles成员变量赋值,这会导致计算打击率时始终忽略二垒安打的数量,结果肯定不准确!上面的代码已经帮你补上了这个参数和赋值,记得传入实际的doubles数值哦。
修改完成后运行,输出就会是你想要的.345,而不是0.345啦。
内容的提问来源于stack exchange,提问作者StaceyM
相关产品推荐
相关产品推荐

