digit.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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} \u8D85\u51FA\u4E86\u7CBE\u5EA6\u9650\u5236\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u6B63\u786E`);
  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(num1Changed / num2Changed, strip(Math.pow(10, digitLength(num2) - digitLength(num1))));
  54. }
  55. function round(num, ratio) {
  56. const base = Math.pow(10, ratio);
  57. let result = divide(Math.round(Math.abs(times(num, base))), base);
  58. if (num < 0 && result !== 0) {
  59. result = times(result, -1);
  60. }
  61. return result;
  62. }
  63. exports.round = round;