小数转成分数
最近在写一个项目,后台返回的是两位小数,让转成分数,网上找了下资料,直接上代码记录下:
const decimalsToFractional = (decimals) => { const formatDecimals = decimals; 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}` }