Nessuna descrizione

index.js 804B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict'
  2. var abs = Math.abs
  3. var round = Math.round
  4. function almostEq(a, b) {
  5. return abs(a - b) <= 9.5367432e-7
  6. }
  7. //最大公约数 Greatest Common Divisor
  8. function GCD(a, b) {
  9. if (almostEq(b, 0)) return a
  10. return GCD(b, a % b)
  11. }
  12. function findPrecision(n) {
  13. var e = 1
  14. while (!almostEq(round(n * e) / e, n)) {
  15. e *= 10
  16. }
  17. return e
  18. }
  19. function num2fraction(num) {
  20. if (num === 0 || num === '0') return '0'
  21. if (typeof num === 'string') {
  22. num = parseFloat(num)
  23. }
  24. var precision = findPrecision(num) //精确度
  25. var number = num * precision
  26. var gcd = abs(GCD(number, precision))
  27. //分子
  28. var numerator = number / gcd
  29. //分母
  30. var denominator = precision / gcd
  31. //分数
  32. return round(numerator) + '/' + round(denominator)
  33. }
  34. module.exports = num2fraction