unis_sip/oms_web/oms_vue/src/utils/calc.js

39 lines
921 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import Decimal from 'decimal.js'
// 默认保留小数位(你可根据业务修改,比如金额一般 2 位)
const DEFAULT_DP = 2
// 内部方法:统一转换 Decimal避免 null/undefined 报错
function D(n) {
return new Decimal(n || 0)
}
/**
* 保留小数位 & 四舍五入
* @param value 数值
* @param dp 保留位数(默认 DEFAULT_DP
*/
export function toFixed(value, dp = DEFAULT_DP) {
return D(value).toDecimalPlaces(dp).toNumber()
}
// 加法
export function add(a, b, dp = DEFAULT_DP) {
return D(a).plus(b).toDecimalPlaces(dp).toNumber()
}
// 减法
export function sub(a, b, dp = DEFAULT_DP) {
return D(a).minus(b).toDecimalPlaces(dp).toNumber()
}
// 乘法
export function mul(a, b, dp = DEFAULT_DP) {
return D(a).times(b).toDecimalPlaces(dp).toNumber()
}
// 除法
export function div(a, b, dp = DEFAULT_DP) {
return D(a).div(b || 1).toDecimalPlaces(dp).toNumber()
}