如何摆脱小数点之前的小数点之前的前导零? [英] How to get rid of leading zero before the decimal point in a double less than one?

查看:192
本文介绍了如何摆脱小数点之前的小数点之前的前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个相当大的项目(对我来说,是高中的AP JAVA课程)。无论如何,对于项目的一部分,我需要能够四舍五入一个小数,并输出它没有在小数点前的零开始。



例如:.4999轮---> 0.5
我需要:.4999轮---> .5



提前致谢

解决方案

试试这个:

  public static String format(double value,int decimalPlaces){
if(value> 1 || value< 0){
throw new IllegalArgumentException 值必须在0和1之间);
}
final String tmp = String.format(%。+ decimalPlaces +f,value);
return tmp.substring(tmp.indexOf('。'));





$ b <$>

  System.out.println(format(0.4999d,1)); // .5 
System.out.println(format(0.0299d,2)); // .03
System.out.println(format(0.34943d,3)); // .349

工作小提琴


I am doing a rather large project (for me, is an AP JAVA course in high school). Anyways, for a portion of the project I need to be able to round a decimal and output it without the zero at the beginning before the decimal.

Ex: .4999 rounds ---> 0.5 I need: .4999 round ---> .5

Thanks in advance

解决方案

Try this:

public static String format(double value, int decimalPlaces) {
   if (value >= 1 || value < 0) {
      throw new IllegalArgumentException("Value must be between 0 and 1");
   }
   final String tmp = String.format("%." + decimalPlaces + "f", value);
   return tmp.substring(tmp.indexOf('.'));
}

Examples:

System.out.println(format(0.4999d, 1)); // .5
System.out.println(format(0.0299d, 2)); // .03
System.out.println(format(0.34943d, 3)); // .349

Working Fiddle

这篇关于如何摆脱小数点之前的小数点之前的前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆