Last change
on this file since 6fe77af was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
804 bytes
|
Line | |
---|
1 | 'use strict'
|
---|
2 |
|
---|
3 | var abs = Math.abs
|
---|
4 | var round = Math.round
|
---|
5 |
|
---|
6 | function almostEq(a, b) {
|
---|
7 | return abs(a - b) <= 9.5367432e-7
|
---|
8 | }
|
---|
9 |
|
---|
10 | //最大公约数 Greatest Common Divisor
|
---|
11 | function GCD(a, b) {
|
---|
12 | if (almostEq(b, 0)) return a
|
---|
13 | return GCD(b, a % b)
|
---|
14 | }
|
---|
15 |
|
---|
16 | function findPrecision(n) {
|
---|
17 | var e = 1
|
---|
18 |
|
---|
19 | while (!almostEq(round(n * e) / e, n)) {
|
---|
20 | e *= 10
|
---|
21 | }
|
---|
22 |
|
---|
23 | return e
|
---|
24 | }
|
---|
25 |
|
---|
26 | function num2fraction(num) {
|
---|
27 | if (num === 0 || num === '0') return '0'
|
---|
28 |
|
---|
29 | if (typeof num === 'string') {
|
---|
30 | num = parseFloat(num)
|
---|
31 | }
|
---|
32 |
|
---|
33 |
|
---|
34 | var precision = findPrecision(num) //精确度
|
---|
35 | var number = num * precision
|
---|
36 | var gcd = abs(GCD(number, precision))
|
---|
37 |
|
---|
38 | //分子
|
---|
39 | var numerator = number / gcd
|
---|
40 | //分母
|
---|
41 | var denominator = precision / gcd
|
---|
42 |
|
---|
43 | //分数
|
---|
44 | return round(numerator) + '/' + round(denominator)
|
---|
45 | }
|
---|
46 |
|
---|
47 | module.exports = num2fraction
|
---|
48 |
|
---|
Note:
See
TracBrowser
for help on using the repository browser.