function addArr (arr) {
const fieldArr = []
for (var i = 0; i < arr.length; i++) {
var m, field
try {
field = arr[i].toString().split('.')[1].length
} catch (e) {
field = 0
}
fieldArr.push(field)
}
m = Math.pow(10, Math.max(...fieldArr))
let add = 0
arr.forEach(function (item) {
add = add + item * m
})
// let sum = Math.round(add) / m
let sum = add / m
return sum
};
// 如果参数的小数部分大于 0.5,则舍入到相邻的绝对值更大的整数。
// 如果参数的小数部分小于 0.5,则舍入到相邻的绝对值更小的整数
// x = Math.round(20.49); //20
// x = Math.round(20.5); //21
// x = Math.round(-20.5); //-20
// x = Math.round(-20.51); //-21
// console.log(addArr([0.1,0.2]))
// console.log(addArr([232.423423,3.121]))
// console.log(addArr([0.1,23,0.3])) //23.4
// console.log(0.1+23+0.3) //23.400000000000002
function add (num1, num2) {
var p1 = 0
var p2 = 0
if (num1.toString().split('.').length > 1) {
p1 = num1.toString().split('.')[1].length
}
if (num2.toString().split('.').length > 1) {
p2 = num2.toString().split('.')[1].length
}
var p = p1 > p2 ? p1 : p2
var n1 = num1 * Math.pow(10, p)
var n2 = num2 * Math.pow(10, p)
var result = (n1 + n2) / Math.pow(10, p)
return result
}
// console.log(add(0.1,0.2))
// console.log(add(232.423423,3.121),'11') //235.544423
// console.log(232.423423+ 3.121,'22') //235.54442300000002
// 如果是3个数相加
// 求出三个数字的最大值
// a>b ? (a>c ? a:c):(b>c ? b:c);
function add3 (num1, num2, num3) {
var p1 = 0
var p2 = 0
var p3 = 0
if (num1.toString().split('.').length > 1) {
p1 = num1.toString().split('.')[1].length
}
if (num2.toString().split('.').length > 1) {
p2 = num2.toString().split('.')[1].length
}
if (num3.toString().split('.').length > 1) {
p3 = num3.toString().split('.')[1].length
}
var p = p1>p2 ? (p1>p3 ? p1:p3):(p2>p3 ? p2:p3)
var n1 = num1 * Math.pow(10, p)
var n2 = num2 * Math.pow(10, p)
var n3 = num3 * Math.pow(10, p)
var result = (n1 + n2+ n3) / Math.pow(10, p)
return result
}
console.log(add3(0.1,23,0.3))
相加精度缺失问题
最新推荐文章于 2024-11-05 22:07:06 发布