
正文
java精确的小数类代码 java怎么精确小数点
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
请问:在Java语言中如何把一个浮点数精确到小数点后的某几位?
-- Math.round()
(double) (Math.round(sd3*10000)/10000.0);
这样为保持4位
(double) (Math.round(sd3*100)/100.0);
这样为保持2位.
-- BigDecimal
//保留小数点后两位小数
public double Number2(double pDouble)
{
BigDecimal bd=new BigDecimal(pDouble);
BigDecimal bd1=bd.setScale(2,bd.ROUND_HALF_UP);
pDouble=bd1.doubleValue();
long ll = Double.doubleToLongBits(pDouble);
return pDouble;
}
格式化输出数字
-- NumberFormat
--java.text 包中的一些包可以处理这类问题。下面的简单范例使用那些类解决上面提出的问题:
import java.text.NumberFormat;
import java.util.Locale;
public class DecimalFormat1 {
public static void main(String args[]) {
// 得到本地的缺省格式
NumberFormat nf1 = NumberFormat.getInstance();
System.out.println(nf1.format(1234.56));
// 得到德国的格式
NumberFormat nf2 =
NumberFormat.getInstance(Locale.GERMAN);
System.out.println(nf2.format(1234.56));
}
}
-- DecimalFormat
import java.text.DecimalFormat;
import java.util.Locale;
public class DecimalFormat2 {
public static void main(String args[]) {
// 得到本地的缺省格式
DecimalFormat df1 = new DecimalFormat("####.000");
System.out.println(df1.format(1234.56));
// 得到德国的格式
Locale.setDefault(Locale.GERMAN);
DecimalFormat df2 = new DecimalFormat("####.000");
System.out.println(df2.format(1234.56));
}
}
相关问答
Q1: java怎样精确小数点???
.1.(double) (Math.round(sd3*10000)/10000.0);
这样为保持4位
(double) (Math.round(sd3*100)/100.0);
这样为保持2位.
2.另一种办法
import java.text.DecimalFormat;
DecimalFormat df2 = new DecimalFormat("###.00");
DecimalFormat df2 = new DecimalFormat("###.000");
System.out.println(df2.format(doube_var));
第一个为2位,第二个为3位.
Q2: java怎样精确到小数点后20位
java精确的小数类代码我们先确定一个有10位小数java精确的小数类代码的double类型java精确的小数类代码,double a=10.1234567891(10位小数)
double b=10.1234567892(10位小数)
double c=a*b=10.1234567891*10.1234567892(可以确定c的值有20位小数java精确的小数类代码,即精确到20位,至于20位以后,只需要给a或b在10.1234567891后添个2,即10.12345678912,变量C就可以精确到21位)
Q3: java中小数怎么四舍五入?
按照你java精确的小数类代码的要求为不确定保留几位小数java精确的小数类代码的字符串做四舍五入的Java程序如下
import java.math.BigDecimal;
public class A {
public static void main(String[] args) {
String s="0.00000999999997";
//四舍五入,length是小数位数
int length=s.substring(s.indexOf(".")+1).length();
String s1=String.format("%."+(length-1)+"f",new BigDecimal(s));
//去尾部0
BigDecimal bd=new BigDecimal(s1).stripTrailingZeros();
System.out.println(bd.toPlainString());
}
}
java精确的小数类代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java怎么精确小数点、java精确的小数类代码的信息别忘了在本站进行查找喔。






