题目描述

汇率计算:输出 price * rate的结果,如:100.01 * 7.3215 的结果,并规避JS浮点数计算精度问题

思路&js代码

1、使用整数进行计算

function getInt(num) {
	// 小数位数
  const count = num.match(/\.\d+/)?.[0].length - 1 || 0
	// 整数的值
  const int = Number(num.replace(".", ""))
 
  return {
    count,
    int,
  }
}
 
function calcRates(num1, num2) {
  const { int: int1, count: count1 } = getInt(num1)
  const { int: int2, count: count2 } = getInt(num2)
 
  const result = (int1 * int2) / Math.pow(10, count1 + count2)
 
  console.log(count1, count2, result)
 
  return result
}
 
calcRates("1.11", "23145")