怎么才能不用写那么多parseFloat强制转换不相干的代码? - CNode技术社区

怎么才能不用写那么多parseFloat强制转换不相干的代码?
发布于 10 年前 作者 liuxufei 3619 次浏览 最后一次编辑是 9 年前 来自 问答

toFixed 为如下代码

Number.prototype._toFixed = Number.prototype._toFixed || Number.prototype.toFixed;
Number.prototype.toFixed = function(precision) {
 return (+(Math.round(+(this + 'e' + precision)) + 'e' + -precision))._toFixed(precision);
}

示例代码:

var math = require('mathjs');
math.config({
 number: 'BigNumber',
 precision: 64,
});
exports.aaa = function (req, res, next) {
 
 // 问题:需要写太多parseFloat转换不相干代码,烦啊
 return models.Site.findOne({
 where: {
 name: config.code,
 },
 }).then(function (site) {
 
 // 问题1:比对
 console.log(site.mmm); // 输出:13.00000000。获取的数据库值为 13.000000,这里的值应该是 string 类型。
 console.log(typeof(site.mmm)); // 输出:string
 // var aaa = 2;
 var aaa = '2';
 console.log(aaa); // 输出:2
 console.log(typeof(aaa)); // 输出:int
 // var aaa = math.eval(parseFloat(2)).toFixed(8); // 需要保留8位小数位数,如上 toFixed
 aaa = math.eval(aaa).toFixed(8); // 需要保留8位小数位数,如上 toFixed
 // var aaa = 2;
 console.log(aaa); // 输出:2.00000000
 console.log(typeof(aaa)); // 输出:string
 console.log('--------------------------');
 
 if (aaa > site.mmm) { // 输出:err。错误,得到结果为 err。因为 site.mmm 为 string 类型。
 console.log('err');
 } else {
 console.log('succ');
 }
 if (aaa > parseFloat(site.mmm)) { // 输出:succ。正确,得到的结果为 succ。
 console.log('err');
 } else {
 console.log('succ');
 }
 if (parseFloat(aaa) > parseFloat(site.mmm)) { // 输出:succ。正确,得到的结果为 succ。
 console.log('err');
 } else {
 console.log('succ');
 }
 console.log('--------------------------');
 
 // 问题2:计算
 // var bbb1 = math.eval(aaa + site.mmm).toFixed(8); // 直接出错
 var bbb2 = math.eval(aaa + parseFloat(site.mmm)).toFixed(8);
 var bbb3 = math.eval(parseFloat(aaa) + parseFloat(site.mmm)).toFixed(8);
 // var bbb4 = math.eval(aaa + site.mmm); // 直接出错
 var bbb5 = math.eval(aaa + parseFloat(site.mmm));
 var bbb6 = math.eval(parseFloat(aaa) + parseFloat(site.mmm));
 
 // console.log('bbb1:' + bbb1);
 console.log('bbb2:' + bbb2); // bbb2:2.00000000 得到的值错误
 console.log('bbb3:' + bbb3); // bbb3:15.00000000 得到的值正确
 // console.log('bbb4' + bbb4);
 console.log('bbb5:' + bbb5); // bbb5:2.0000000013 得到的值错误
 console.log('bbb6:' + bbb6); // bbb6:15 得到的值正确
 console.log('--------------------------');
 });
};

怎么才能不用写那么多parseFloat强制转换不相干的代码?

回到顶部

AltStyle によって変換されたページ (->オリジナル) /