digit.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. function strip(num, precision = 15) {
  3. return +parseFloat(Number(num).toPrecision(precision));
  4. }
  5. function digitLength(num) {
  6. const eSplit = num.toString().split(/[eE]/);
  7. const len = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0);
  8. return len > 0 ? len : 0;
  9. }
  10. function float2Fixed(num) {
  11. if (num.toString().indexOf("e") === -1) {
  12. return Number(num.toString().replace(".", ""));
  13. }
  14. const dLen = digitLength(num);
  15. return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num);
  16. }
  17. function checkBoundary(num) {
  18. {
  19. if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
  20. console.warn(`${num} 超出了精度限制,结果可能不正确`);
  21. }
  22. }
  23. }
  24. function iteratorOperation(arr, operation) {
  25. const [num1, num2, ...others] = arr;
  26. let res = operation(num1, num2);
  27. others.forEach((num) => {
  28. res = operation(res, num);
  29. });
  30. return res;
  31. }
  32. function times(...nums) {
  33. if (nums.length > 2) {
  34. return iteratorOperation(nums, times);
  35. }
  36. const [num1, num2] = nums;
  37. const num1Changed = float2Fixed(num1);
  38. const num2Changed = float2Fixed(num2);
  39. const baseNum = digitLength(num1) + digitLength(num2);
  40. const leftValue = num1Changed * num2Changed;
  41. checkBoundary(leftValue);
  42. return leftValue / Math.pow(10, baseNum);
  43. }
  44. function divide(...nums) {
  45. if (nums.length > 2) {
  46. return iteratorOperation(nums, divide);
  47. }
  48. const [num1, num2] = nums;
  49. const num1Changed = float2Fixed(num1);
  50. const num2Changed = float2Fixed(num2);
  51. checkBoundary(num1Changed);
  52. checkBoundary(num2Changed);
  53. return times(
  54. num1Changed / num2Changed,
  55. strip(Math.pow(10, digitLength(num2) - digitLength(num1)))
  56. );
  57. }
  58. function round(num, ratio) {
  59. const base = Math.pow(10, ratio);
  60. let result = divide(Math.round(Math.abs(times(num, base))), base);
  61. if (num < 0 && result !== 0) {
  62. result = times(result, -1);
  63. }
  64. return result;
  65. }
  66. exports.round = round;