About how to keep decimal calculation function in js development (keep decimal by rounding up or down)

Keywords: Javascript less

In front-end work, we often encounter the problem of keeping decimal in number calculation. Because the toFixed function can't be used instead of rounding, this paper uses the method of regular expression matching string to solve the problem of keeping decimal in number up or down:

1. Keep the decimal up (enter 1 as long as there is a significant number after the target decimal place, and ensure that the calculated value is not less than the original value)

function upFixed (num, fix) {
  // num Is the original number, fix Is the number of decimal places reserved
  let result = '0'
  if (Number(num) && fix > 0) { // Make a simple judgment
    fix = +fix || 2
    num = num + ''
    if (/e/.test(num)) { // If it contains e Number of characters returned directly
      result = num
    } else if (!/\./.test(num)) { // If there is no decimal point
      result = num + `.${Array(fix + 1).join('0')}`
    } else { // If there is a decimal point
      num = num + `${Array(fix + 1).join('0')}`
      let reg = new RegExp(`-?\\d*\\.\\d{0,${fix}}`)
      let floorStr = reg.exec(num)[0]
      if (+floorStr >= +num) {
        result = floorStr
      } else {
        let floorNumber = +floorStr + +`0.${Array(fix).join('0')}1`
        let point = /\./.test(floorNumber + '') ? '' : '.'
        let floorStr2 = floorNumber + point + `${Array(fix + 1).join('0')}`
        result = reg.exec(floorStr2)[0]
      }
    }
  }
  return result
}

2. Keep decimals downward (the numbers after the target decimals will be discarded directly to ensure that the calculated value is not greater than the original value)

function downFixed (num, fix) {
  // num Is the original number, fix Is the number of decimal places reserved
  let result = '0'
  if (Number(num) && fix > 0) { // Make a simple judgment
    fix = +fix || 2
    num = num + ''
    if (/e/.test(num)) { // If it contains e Number of characters returned directly
      result = num
    } else if (!/\./.test(num)) { // If there is no decimal point
      result = num + `.${Array(fix + 1).join('0')}`
    } else { // If there is a decimal point
      num = num + `${Array(fix + 1).join('0')}`
      let reg = new RegExp(`-?\\d*.\\d{0,${fix}}`)
      result = reg.exec(num)[0]
    }
  }
  return result
}

Note: this method does not process the numbers with scientific counting method and returns them directly

Another: the two functions are very similar, and can be combined and optimized according to their own needs

If you find any problems, please let me know

Posted by zurron on Tue, 03 Dec 2019 20:49:26 -0800