js小数转分数-近似递归

精度为小数两位,提高精度可把 toFixed(2)和100同时修改;

 

function decimalsToFractional(decimals){
    const formatDecimals = decimals.toFixed(2)
    let denominator = 100 //初始化分母
    let numerator  = formatDecimals * 100 //初始化分子
    let bigger = 0
    function  recursion (){
        bigger = denominator > numerator ? denominator : numerator
        for(let i = bigger; i > 1; i--){
            if(
                Number.isInteger(numerator/i)
                && Number.isInteger(denominator/i)){
                numerator=numerator/i
                denominator=denominator/i
                recursion()
            }
        }
    }
    recursion()
    return `${numerator}/${denominator}`
}

 

posted @ 2018-03-23 17:33  酒丨剑丨仙  阅读(2436)  评论(0编辑  收藏  举报