zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java怎样解决除法精度_java 除法 精度问题

JAVA 问题 解决 怎样 精度 除法
2023-06-13 09:11:59 时间

大家好,又见面了,我是你们的朋友全栈君。

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(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果为12,Math.round(-11.5)的结果为-11。 Math.floor(1.4)=1.0 Math.round(1.4)=1 Math.ceil(1.4)=2.0 Math.floor(1.5)=1.0 Math.round(1.5)=2 Math.ceil(1.5)=2.0 Math.floor(1.6)=1.0 Math.round(1.6)=2 Math.ceil(1.6)=2.0 Math.floor(-1.4)=-2.0 Math.round(-1.4)=-1 Math.ceil(-1.4)=-1.0 Math.floor(-1.5)=-2.0 Math.round(-1.5)=-1 Math.ceil(-1.5)=-1.0 Math.floor(-1.6)=-2.0 Math.round(-1.6)=-2 Math.ceil(-1.6)=-1.0

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/135139.html原文链接:https://javaforall.cn