js 格式科学计数

  • 问题
    js进行浮点运算时, 有时得到结果不精确, 小数位过长会自动科学计数表示, 往后运算, 有时程序会产生小BUG
let i = 1
let res

let timerId = setInterval(() => {
  // 每隔100ms, i-0.2
  i -= 0.2
  console.log("origin ---", i) // 原数据
  res = parseInt(i)
  console.log("processed ---", res) // 模拟进行处理后数据, parseInt为例
  if(res>1) console.log("*** wrong ***")
  // i<0 关闭定时器
  if(i<0) clearInterval(timerId)
}, 100)

控制台打印结果
js 格式科学计数_第1张图片

  • 解决方法
    利用toFixed()规避科学计数法
    需注意的是toFixed()会返回String, 有必要的还要进行parseInt | parseFloat
let i = 1
let res
console.log(typeof 2.5.toFixed(1)) // toFixed() 返回值为String
let timerId = setInterval(() => {

  i -= 0.2
  console.log("origin ---", i) 
  res = parseInt(i.toFixed(2)) // toFixed()避免科学计数
  console.log("processed ---", res) 
  if(res>1) console.log("*** wrong ***")
  
  if(i<0) clearInterval(timerId)
}, 100)

控制台打印结果
js 格式科学计数_第2张图片

你可能感兴趣的:(javascript,javascript,bug)