import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class Test {
/**
* 保留2位小数
*
* @param money
* 金额
* @param scale
* 精度
* @return
*/
public static String ratioTransform(double money) {
BigDecimal moneyDev = new BigDecimal(money).setScale(2,
RoundingMode.HALF_UP);
return moneyDev.toString();
}
/**
* 保留2位小数
*
* @param money
* 金额
* @param scale
* 精度
* @return
*/
public static String ratioTransform2(double money) {
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
return df.format(money);
}
public static void main(String[] arg) {
/** 输出14.00 */
System.out.println(ratioTransform(14.00));
System.out.println(ratioTransform2(14.00));
/** 输出14.12 */
System.out.println(ratioTransform(14.115));
System.out.println(ratioTransform2(14.115));
/** 输出12345.68 */
System.out.println(ratioTransform(12345.6789));
System.out.println(ratioTransform2(12345.6789));
}
}
BigDecimal精度问题
最新推荐文章于 2024-07-10 22:10:34 发布