元与万元转换,以及千分符、保留两位处理等。

// 元转万元
const setIsNumer = (num, isToFix = true) => {
  let result;
  if (num !== null && !isNaN(parseFloat(num))) {
	const newNum = parseFloat(parseFloat(num.toString().replace(/,/gi, '')) / 10000);
	if (isToFix) {
	  // 如果需要四舍五入
	  result = parseFloat(newNum.toFixed(2));
	} else {
	  // 不需要四舍五入 精度问题会补1最后一位
	  // result = parseFloat(
	  //   Util.Math.div(Math.floor(Util.Math.mul(newNum, 100)), 100),
	  // );
	  result = setNumberToFixed(newNum);
	}
	return result;
  }
  return null;
};

// 万元转元
const setWanYuanNumber = (num, isToFix = true) => {
  if (num !== null && !isNaN(parseFloat(num))) {
	const value = parseFloat(parseFloat(num) * 10000);
	if (isToFix) {
	  return value.toFixed(2);
	} else {
	  return setNumberToFixed(value);
	}
  }
  return null;
};

// 数字保留两位小数 且不四舍五入
const setNumberToFixed = (num) => {
  if (num !== null && !isNaN(parseFloat(num))) {
	num = num.toString().replaceAll(',', ''); //有的数据后端做了千分位处理
	const arrayNum = num.toString().split('.');
	if (arrayNum?.length === 1) {
	  // 整数补0
	  return num.toString() + '.00';
	}
	let [int, flot] = arrayNum;
	flot = flot?.substring(0, 2) ? flot?.substring(0, 2) : 0;
	return parseFloat(`${int}.${flot}`).toFixed(2);
  } else {
	return null;
  }
};

// 整数带小数千分位分割
const setNumberDivision = (value) => {
  return isNaN(parseFloat(value))
	? null
	: value
	  .toString()
	  // : parseFloat(value)
	  //     .toString()
	  .replace(/\B(?<!(\.\d+))(?=(\d{3})+\b)/g, ',');
};

//  千分位分割,保留2位小数(不四舍五入)
const setNumberDivisionToFixed = (value) => {
  return setNumberDivision(setNumberToFixed(value));
};
posted @ 2024-05-08 10:36  SKa-M  阅读(15)  评论(0编辑  收藏  举报