a zip code crypto-currency system good for red ONLY

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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