1. 程式人生 > >java精確的乘法和除法

java精確的乘法和除法

import java.math.BigDecimal;

public class 乘除 {
	public static void main(String[] args) {
		double a = 4.123;
		double b = 2;
		System.out.println(hehe(a,b));
	}

	private static String hehe(double a, double b) {
		BigDecimal b1 = new BigDecimal(String.valueOf(a));
		BigDecimal b2 = new BigDecimal(String.valueOf(b));
		BigDecimal bb = b1.divide(b2,3,BigDecimal.ROUND_HALF_UP);
		Double bbb = bb.doubleValue();
		return String.valueOf(bbb);
		
	}
}
import java.math.BigDecimal;

public class 乘除 {
	public static void main(String[] args) {
		double a = 4.123;
		double b = 2;
		System.out.println(hehe(a,b));
	}

	private static String hehe(double a, double b) {
		BigDecimal b1 = new BigDecimal(String.valueOf(a));
		BigDecimal b2 = new BigDecimal(String.valueOf(b));
		BigDecimal nn = b1.multiply(b2);
		BigDecimal nnn = nn.setScale(2, BigDecimal.ROUND_HALF_UP);
		return String.valueOf(nnn);
	}
}