四舍五入双在Java ME 5位小数(Rounding a double to 5 decimal

2019-07-18 16:40发布

如何圆一个双到5位小数,而无需使用DecimalFormat

Answer 1:

您可以通过它你数乘以第一位小数四舍五入到第五位小数。 然后做正常的四舍五入,再次使其成为第五位小数。

比方说圆的值是一个double命名为x

double factor = 1e5; // = 1 * 10^5 = 100000.
double result = Math.round(x * factor) / factor;

如果你想四舍五入到小数点后6位,让factor1e6 ,等等。



Answer 2:

不管你做什么,如果你结束了一个double值它不可能正好是5个位小数。 这只是不是二进制浮点运算的工作方式。 你会做的最好的是“ 最接近的double值四舍五入到5位小数的原始值”。 如果你要打印出双倍的精确值,也仍然可能有超过5位小数。

如果你真的想精确十进制值,你应该使用BigDecimal



Answer 3:

乘以100000添加0.5。 截断为整数。 然后为100000mPa分裂。

码:

double original = 17.77777777;
int factor = 100000;
int scaled_and_rounded = (int)(original * factor + 0.5);
double rounded = (double)scaled_and_rounded / factor;


Answer 4:

如果你是好与外部库,你可以看看microfloat ,特别是MicroDouble.toString(双d,INT长度) 。



Answer 5:

请尝试以下

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 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));

问候,



Answer 6:

DecimalFormat roundFormatter = new DecimalFormat("########0.00000");

public Double round(Double d)
    {
        return Double.parseDouble(roundFormatter.format(d));
    }


Answer 7:

public static double roundNumber(double num, int dec) {
        return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}


Answer 8:

我偶然发现在这里寻找一种方式,以我的双号限制到小数点后两位,所以不会截断也不舍入。 Math.Truncate为您提供了双号的组成部分,小数点后丢弃一切,所以10.123456截断后,变成10。 Math.Round四舍五入到最接近的整数值的数量,以便10.65变为11,而10.45于是变成10.这两个功能不符合我的需要(我想,净已重载这两个允许截断或四舍五入到一定小数位数)。 做什么,我需要最简单的方法是:

//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);


文章来源: Rounding a double to 5 decimal places in Java ME