如何在不使用DecimalFormat
?
答案 0 :(得分:14)
您可以通过乘以数字将其作为第一个小数位来舍入到小数点后五位。然后进行正常舍入,再次将其作为小数点后第五位。
假设圆的值是名为double
的{{1}}:
x
如果要舍入到6位小数,请double factor = 1e5; // = 1 * 10^5 = 100000.
double result = Math.round(x * factor) / factor;
为factor
,依此类推。
答案 1 :(得分:10)
无论你做什么,如果你得到一个double
值,它就不可能完全 5个小数位。这不是二进制浮点运算的工作方式。你要做的最好的是“双值最接近到原始值四舍五入到5位小数”。如果您打印出该双精度的精确值,它仍可能有超过5个小数位。
如果确实想要精确的十进制值,则应使用BigDecimal
。
答案 2 :(得分:8)
乘以100000.加0.5。截断为整数。然后除以100000。
代码:
double original = 17.77777777;
int factor = 100000;
int scaled_and_rounded = (int)(original * factor + 0.5);
double rounded = (double)scaled_and_rounded / factor;
答案 3 :(得分:3)
如果您对外部库感到满意,可以查看microfloat,特别是MicroDouble.toString(double d, int length)。
答案 4 :(得分:2)
尝试以下
double value = Double.valueOf(String.format(Locale.US, "%1$.5f", 5.565858845));
System.out.println(value); // prints 5.56586
value = Double.valueOf(String.format(Locale.US, "%1$.5f", 5.56585258));
System.out.println(value); // prints 5.56585
或者如果您想要最少量的代码
使用import static
import static java.lang.Double.valueOf;
import static java.util.Locale.US;
import static java.lang.String.format;
和
double value = valueOf(format(US, "%1$.5f", 5.56585258));
的问候,
答案 5 :(得分:2)
DecimalFormat roundFormatter = new DecimalFormat("########0.00000");
public Double round(Double d)
{
return Double.parseDouble(roundFormatter.format(d));
}
答案 6 :(得分:1)
public static double roundNumber(double num, int dec) {
return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}
答案 7 :(得分:0)
我偶然发现这里寻找一种方法来限制我的双倍数到两位小数,所以不要截断或舍入它。 Math.Truncate为您提供双数的整数部分,并丢弃小数点后的所有内容,因此截断后10.123456变为10。 Math.Round将数字四舍五入到最接近的整数值,因此10.65变为11而10.45变为10.所以这两个函数都不符合我的需要(我希望.Net已经超载了这两个以允许截断或舍入到某个小数位数)。做我需要的最简单的方法是:
//First create a random number
Random rand = new Random();
//Then make it a double by getting the NextDouble (this gives you a value
//between 0 and 1 so I add 10 to make it a number between 10 and 11
double chn = 10 + rand.NextDouble();
//Now convert this number to string fixed to two decimal places by using the
//Format "F2" in ToString
string strChannel = chn.ToString("F2");
//See the string in Output window
System.Diagnostics.Debug.WriteLine("Channel Added: " + strChannel);
//Now convert the string back to double so you have the double (chn)
//restricted to two decimal places
chn = double.Parse(strChannel);