概述
int a=4;
int b=3;
float c = (float) a/b;
System.out.print(c);//输出:1
如果要的到精确的结果,要用下面的方法
int a=4;
int b=3;
float c = (float) a/(float) b;
System.out.print(c);//输出:1.3333334
import java.text.DecimalFormat;
public class toDouble {
public static void main(String[] args){
//增加三位小数0
DecimalFormat df = new DecimalFormat("0.000");
double d = 123;
System.out.println(df.format(d));
//保留4位小数
double d1 = 123.0123456;
String d2 = String.format("%.4f", d1);
System.out.println(d2);
int d3=5;
//float d4=d3/100;
String d4 = String.format("%.3f", (float)d3/100.00);
System.out.println(d4);
}
}
输出:123.000
123.0123
0.050
Java除法保留3位小数的几种方法
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class format {
double f = 0.5585;
double f1 = 11.5585;
public void m1() {
//数字
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
}
/**
* DecimalFormat转换最简便
*/
public void m2() {
//字符串
DecimalFormat df = new DecimalFormat("0.000");//对于大于1的用"#.000",小于1的要用"0.000"
String t=df.format(f);
System.out.println(t);
DecimalFormat df1 = new DecimalFormat("#.000");
System.out.println(df1.format(f1));
}
/**
* String.format打印最简便
*/
public void m3() {
//字符串
String t =String.format("%.3f", f);
System.out.println(t);
}
public void m4() {
//字符串
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(3);
String t =nf.format(f);
System.out.println(t);
}
public static void main(String[] args) {
format f = new format();
f.m1();
f.m2();
f.m3();
f.m4();
}
}
结果:
0.558
0.558
11.558
0.559
0.558
Math.ceilMath.roundMath.floor
floor 向下取整ceil 向上取整round 则是4舍5入的计算,round方法,它表示“四舍五入”,Math.floor(1.4)=1.0Math.round(1.4)=1Math.ceil(1.4)=2.0Math.floor(1.5)=1.0Math.round(1.5)=2Math.ceil(1.5)=2.0Math.floor(1.6)=1.0Math.round(1.6)=2Math.ceil(1.6)=2.0Math.floor(-1.4)=-2.0Math.round(-1.4)=-1Math.ceil(-1.4)=-1.0Math.floor(-1.5)=-2.0Math.round(-1.5)=-1Math.ceil(-1.5)=-1.0Math.floor(-1.6)=-2.0Math.round(-1.6)=-2Math.ceil(-1.6)=-1.0
最后
以上就是心灵美小鸭子为你收集整理的java 除法 精度_java 除法 精度问题 | 学步园的全部内容,希望文章能够帮你解决java 除法 精度_java 除法 精度问题 | 学步园所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复