java 两个整数相除保留两位小数

本文介绍了使用Java进行精确的小数除法运算的两种方法。第一种方法利用BigDecimal类进行除法并设置保留两位小数;第二种方法通过DecimalFormat类格式化输出结果。这两种方式都避免了直接使用浮点数除法带来的精度问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.com.itrus;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

	public static void main(String[] args) throws ParseException {
		int a=1099;
		int b=93;
		double f1 = new BigDecimal((float)a/b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		System.out.println("ddd==="+f1);

	}
}


2.第二种

package cn.com.itrus;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

	public static void main(String[] args) throws ParseException {
		int a=1099;
		int b=93; 
		DecimalFormat df = new DecimalFormat("0.00");//格式化小数  
		String num = df.format((float)a/b);//返回的是String类型  
		System.out.println("ddd==="+num);

	}
}
输出结果为  ddd===11.82

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值