|
|
@@ -146,11 +146,11 @@ export function handleRequestBigNumber(value: string) {
|
|
|
* @param value
|
|
|
* @param decimal 保留小数位
|
|
|
*/
|
|
|
-export function parsePercent(value = 0, decimal = 2) {
|
|
|
+export function parsePercent(value = 0, decimal = 2, round = false) {
|
|
|
if (Number.isNaN(value)) {
|
|
|
return '0%'
|
|
|
}
|
|
|
- const val = formatDecimal(value * 100, decimal, false)
|
|
|
+ const val = formatDecimal(value * 100, decimal, round)
|
|
|
return val + '%'
|
|
|
}
|
|
|
|
|
|
@@ -191,27 +191,21 @@ export function pow(base:number, exponent:number) {
|
|
|
* @param round 是否四舍五入
|
|
|
* @returns
|
|
|
*/
|
|
|
-export function formatDecimal(value: number | string, decimal = 2, round = true) {
|
|
|
- const val = Number(value)
|
|
|
- if (decimal <= 0) {
|
|
|
- if (round) {
|
|
|
- return Math.round(val).toString()
|
|
|
- }
|
|
|
- return Math.trunc(val).toString()
|
|
|
- } else {
|
|
|
- if (round) {
|
|
|
- const res = val.toFixed(decimal)
|
|
|
- return res === '-0.00' ? '0.00' : res // 计算精度丢失,临时处理,只适合两位小数
|
|
|
- }
|
|
|
- let num = val.toString()
|
|
|
- const index = num.indexOf('.')
|
|
|
- if (index !== -1) {
|
|
|
- num = num.substring(0, decimal + index + 1)
|
|
|
- } else {
|
|
|
- num = num.substring(0)
|
|
|
- }
|
|
|
- return parseFloat(num).toFixed(decimal)
|
|
|
+export function formatDecimal(value: number | string, decimals = 2, round = true) {
|
|
|
+ const num = Number(value)
|
|
|
+ if (decimals === 0) {
|
|
|
+ // 如果不需要四舍五入,则直接截断(向下取整)
|
|
|
+ return round ? Math.round(num).toString() : Math.floor(num).toString()
|
|
|
+ }
|
|
|
+ if (round) {
|
|
|
+ return num.toFixed(decimals)
|
|
|
}
|
|
|
+ const factor = Math.pow(10, decimals)
|
|
|
+ const truncatedNum = Math.floor(num * factor) / factor
|
|
|
+ const [integerPart, decimalPart = ''] = truncatedNum.toString().split('.')
|
|
|
+ // 补全小数部分到指定位数
|
|
|
+ const zerosToAdd = decimals - decimalPart.length
|
|
|
+ return `${integerPart}.${decimalPart}${zerosToAdd > 0 ? '0'.repeat(zerosToAdd) : ''}`
|
|
|
}
|
|
|
|
|
|
/**
|