The applet retains 2 digits of small data, no rounding

 Method 1: parseInt + toFixed

/*
* 保留2位小数,不四舍五入
* 5.992550 =>5.99 , 2 => 2.00
* */
const toFixed2Decimal = (value) => {
  return (parseInt(value*100)/100).toFixed(2)
}
console.log(587.67*100)
console.log(toFixed2Decimal(587.67))
console.log(toFixed2Decimal(-0.1123456))
console.log(toFixed2Decimal(-1))
console.log(toFixed2Decimal('-12.999'))
console.log(toFixed2Decimal('-12.99999'))
module.exports = {
  toFixed2Decimal: toFixed2Decimal
}

output:

58766.99999999999
587.66

-0.11
-1.00
-12.99
-12.99

 Problem:  587.67 after conversion to 587.66 

Method 2: Math.floor + tofixed

const toFixed2Decimal = (value) => {
  return (Math.floor(value*100)/100).toFixed(2)
}

console.log(toFixed2Decimal(-0.1123456))
console.log(toFixed2Decimal(-1))
console.log(toFixed2Decimal('-12.999'))
console.log(toFixed2Decimal('-12.99999'))

output:

-0.12
-1.00
-13.00
-13.00  

In question -12.99 gives -13.00 

I want to cry. The value of the money obtained by the two methods is wrong.

Guess you like

Origin blog.csdn.net/LlanyW/article/details/132210480