| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- /**
- * 折中方案:处理浮点失真,如果页面卡顿,则需要服务处理
- * @param val
- * @param decimal 需要保留小数位 默认2
- * @param maxCount 最大小数位 超过的时候需要对数值进行处理
- * @returns
- */
- export function getDecimalsNum(val: any, decimal = 2, maxCount = 6) {
- let result = val
- if (typeof val === 'number') {
- const str = val.toString();
- if (str.includes('.')) {
- const num = str.indexOf('.') + 1;
- const count = str.length - num;
- if (count > maxCount) {
- result = val.toFixed(decimal)
- }
- }
- }
- return result
- }
- /**
- * 强制保留小数位,零位四舍五入取整
- * @param value
- * @param decimal 保留小数位 默认2
- * @returns
- */
- export function toDecimalFull(value: number, decimal = 2) {
- if (decimal <= 0) {
- return Math.round(value).toString();
- } else {
- let str = value.toString();
- const num = str.indexOf('.');
- if (num < 0) {
- // 小数位自动补零
- if (decimal > 0) {
- const count = str.length;
- str += '.';
- while (str.length <= count + decimal) {
- str += '0';
- }
- }
- return str;
- }
- return value.toFixed(decimal);
- }
- }
- /**
- * 数字转千位符金额
- * @param value 金额数值
- * @param decimal 保留小数位 默认2
- */
- export function formatAmount(value: number, decimal = 2) {
- const reg = new RegExp('(\\d)(?=(\\d{3})+$)', 'ig');
- const result = value.toFixed(decimal).toString().split('.');
- result[0] = result[0].replace(reg, '$1,');
- return result.join('.');
- }
|