Design a high-precision addition function, which supports the addition of long numbers without losing precision, and ignores negative numbers (please do not use built-in functions such as BCADD)
1. In the past few days, an interview question during the computer test, design a high-precision addition function, which supports the addition of long numbers without losing the accuracy, and ignores negative numbers (please do not use BCADD and other built-in functions).
2. Check php official website, bcadd – the addition calculation of two arbitrary precision numbers. as shown in Figure 1
3. The final realization code is as follows. It is expected to continue to improve after there is time in the future. At this stage, the fault tolerance of request parameters is not enough, and negative numbers are not supported.
9) {
$result[$i + 1] = 1;
}
}
// 将数组转换为字符串并将其反转
$result = strrev(implode($result));
// 计算出小数
$decimal = str_pad(substr($result, -$decimalMaxLen, $scale), $scale, '0');
// 计算出整数
$can = (($maxLen - $decimalMaxLen < 1) ? '0' : substr($result, 0, -$decimalMaxLen));
// 拼接整数与小数
$result = $can . (($scale > 0) ? '.' . $decimal : '');
return $result;
}
echo highPrecisionAdd('64474.47265', '24562.45124');
?>
4. 64474.47265 and 24562.45124 are added, and the operation result is equal to: 89036.92389, which is in line with expectations.
