基于jQuery的小数转分数转换器简化需求及实现问题
实现简化的小数转分数映射方案
嘿,我懂你想要的效果——把那些一位小数简化成更常用的分数,跳过1/10、3/10这类不太顺手的分数对吧?咱们可以通过先给数值做个规则映射,再交给你现有的Fraction处理,就能完美实现你的需求啦!
核心思路
先创建一个映射表,把每个一位小数对应到你想要的目标值,比如把0.1和0.2都映射到0.2(对应1/5),0.9直接映射到1.0(进位成整数),然后把映射后的数值传给你的Fraction转换函数,最后处理一下整数情况的输出即可。
修改后的完整代码
JavaScript部分
function Fraction() {} Fraction.prototype.convert = function(x, improper) { improper = improper || false; var abs = Math.abs(x); this.sign = x / abs; x = abs; var stack = 0; this.whole = !improper ? Math.floor(x) : 0; var fractional = !improper ? x - this.whole : abs; function recurs(x) { stack++; var intgr = Math.floor(x); var dec = (x - intgr); if (dec < 0.0019 || stack > 20) return [intgr, 1]; var num = recurs(1 / dec); return [intgr * num[0] + num[1], num[0]] } var t = recurs(fractional); this.numerator = t[0]; this.denominator = t[1]; } // 重写toString方法,处理整数情况 Fraction.prototype.toString = function() { var l = this.sign.toString().length; var sign = l === 2 ? '-' : ''; // 当没有分数部分时,直接返回整数 if ((this.numerator === 0 && this.whole !== 0) || (this.whole === 0 && this.denominator === 1)) { return sign + (this.sign * (this.whole + this.numerator/this.denominator)).toString(); } var whole = this.whole !== 0 ? this.sign * this.whole + ' ' : sign; return whole + '<sup>' + this.numerator + '</sup>/<sub>' + this.denominator + '</sub>'; } // 定义你的映射规则 const decimalMap = { '0.0': 0, '0.1': 0.2, '0.2': 0.2, '0.3': 0.4, '0.4': 0.4, '0.5': 0.5, '0.6': 0.6, '0.7': 0.8, '0.8': 0.8, '0.9': 1.0 }; // 监听输入实时更新结果 $('#text').on('input', function() { var text = $(this).val(); if (!text || isNaN(parseFloat(text))) { $('#result').html(''); return; } // 先转成一位小数 var digit = parseFloat(text).toFixed(1); // 拆分整数和小数部分 const [wholePart, decimalPart] = digit.split('.'); // 获取映射后的小数值 const mappedDecimal = decimalMap[`0.${decimalPart}`]; // 计算最终要转换的数值 const finalValue = parseInt(wholePart) + mappedDecimal; var frac = new Fraction() frac.convert(finalValue, false) $('#result').html(frac.toString()); });
HTML部分
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="text" value="1.3456" /> <div id="result"></div>
关键改进点
- 映射表:
decimalMap精准对应了你想要的转换规则,确保每个小数位都映射到目标值; - 整数输出处理:修改了
toString方法,当结果是整数时(比如1.0→1,1.9→2),直接输出整数,避免出现多余的分数部分; - 实时响应:添加了输入监听,用户输入时自动更新结果,提升使用体验。
测试效果
输入对应的数值,会得到你想要的结果:
- 1.0 →
1 - 1.1 →
1 <sup>1</sup>/<sub>5</sub> - 1.2 →
1 <sup>1</sup>/<sub>5</sub> - 1.3 →
1 <sup>2</sup>/<sub>5</sub> - 1.4 →
1 <sup>2</sup>/<sub>5</sub> - 1.5 →
1 <sup>1</sup>/<sub>2</sub> - 1.6 →
1 <sup>3</sup>/<sub>5</sub> - 1.7 →
1 <sup>4</sup>/<sub>5</sub> - 1.8 →
1 <sup>4</sup>/<sub>5</sub> - 1.9 →
2
内容的提问来源于stack exchange,提问作者Ashonko
相关产品推荐
相关产品推荐

