Convert a decimal number to a fraction / rational number

前端 未结 11 1838
情歌与酒
情歌与酒 2020-12-01 16:36

In JavaScript, is there any way to convert a decimal number (such as 0.0002) to a fraction represented as a string (such as \"2/10000\")?

I

11条回答
  •  猫巷女王i
    2020-12-01 17:17

    The good news is that it's possible, but you'll have to convert it to code.

    Let's go with 2.56 for no reason at all.

    Use the decimal portion of the number .56

    There are 2 digits in .56, write .56 as 56/100.

    So we have 2 + 56/100 and need to reduce this fraction to lowest terms by dividing both the numerator and denominator by the greatest common divisor, which is 4 in this case.

    So, this fraction reduced to lowest terms is 2 + 14/25.

    To add those whole 2, we multiply by the divisor and add to the 14

    (2*25 + 14)/25 = 64/25

提交回复
热议问题