当前位置:网站首页>Decimal工具类
Decimal工具类
2022-08-09 07:53:00 【CS打赢你】
package cn.xiaobawan.common.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 数学工具类
*/
public class MathUtil {
/**
* 加法
*
* @param a 被加数
* @param b 加数
* @return 结果
*/
public static BigDecimal add(BigDecimal a, BigDecimal b) {
return a.add(b);
}
/**
* 减法
*
* @param a 被减数
* @param b 减数
* @return 结果
*/
public static BigDecimal subtract(BigDecimal a, BigDecimal b) {
return a.subtract(b);
}
/**
* 乘法
*
* @param a 被乘数
* @param b 乘数
* @return 结果
*/
public static BigDecimal multiply(BigDecimal a, BigDecimal b) {
return a.multiply(b);
}
/**
* 除法
*
* @param a 被除数
* @param b 除数
* @return 结果
*/
public static BigDecimal divide(BigDecimal a, BigDecimal b) {
if (0 == a.doubleValue()) { //被除数是零,结果一定为零
return new BigDecimal(0);
}
return a.divide(b, 8, RoundingMode.HALF_UP);
}
/**
* 超过8位就用科学计数法
*
* @param big 传进一个需要格式化的BigDecimal
* @return 返回格式化后字符串
*/
public static String formatData(BigDecimal big) {
String strAll = big.stripTrailingZeros().toPlainString();
int strLength = strAll.contains(".") ? strAll.length() - 1 : strAll.length();
if (strLength > 8) {
String string = big.stripTrailingZeros().toString();
if (string.contains("E")) {
int index = string.indexOf("E");
if ((string.charAt(index + 1) + "").equals("-")) {
return string;
} else {
return new StringBuilder().append(string.substring(0, index + 1))
.append(string.substring(index + 2, string.length())).toString();
}
} else {
return string;
}
} else {
return strAll;
}
}
/**
* 保留小数点后面几位
*
* @param big
* @param bit 要保留的位数
* @return
*/
public static BigDecimal formatKeepDigits(BigDecimal big, int bit) {
return big.setScale(bit, BigDecimal.ROUND_HALF_UP);
}
}
有参考网络一些文章,如有雷同,纯属巧合。
边栏推荐
猜你喜欢
Important news丨.NET Core 3.1 will end support on December 13 this year
如何把无用的代码注释为 Deprecated 弃用
LeetCode: 876. The middle node of the linked list —— simple
Kotlin协程 - 异常处理
链表专项练习(三)
H3C_利用策略路由实现出口双线路负载(选路)的部署
SSM integration development case
The String class objects created by the JVM memory allocation and the difference between equals and = =
Difference Constraint - Graph Theory
定时任务组件Quartz
随机推荐
SDRAM的数据存储实现并对其数据进行读写操作
VOC格式标签转YOLO格式
The String class objects created by the JVM memory allocation and the difference between equals and = =
引导过程与服务控制
EXCEL使用函数联调(find,mid,vlookup,xlookup)
环形链表问题(判环、求入口点)
软件测试的岗位会越来越少吗?
一键登陆服务器脚本
One-click login server script
练习电影卡片、过渡、动画、变形、旋转,练习时钟、立方体、缩放
Invoker 2019CCPC秦皇岛站I题 简单DP
Lottie系列三 :原理分析
Native JDBC operation database
MDK Keil debug时, watch1中全局变量不更新
Exclude null values when Oracle limits
LVM与磁盘配额
Learning Notes---Machine Learning
2017icpc沈阳 G Infinite Fraction Path BFS+剪枝
Apache POI
(四)BP神经网络预测(上)