这个应该算作失真,或者也不算。情况就是用了toFixed后再进行相关计算,得不到预期的结果
具体看例子
比如想动态计算百分比,保留一位小数如94.4%这样子
var blobTo = 409600;
var totalSize = 433927;
var percent = (blobTo / totalSize).toFixed(3) * 100; percent // 94.39999999999999
恰巧碰到这个,然而percent并不是预期的结果。于是,测试各段数据
var blobTo = 409600;
var totalSize = 433927;
var percent1 = (blobTo / totalSize);
var percent2 = (blobTo / totalSize).toFixed(3);
var percent3 = (blobTo / totalSize).toFixed(3) * 100;
var percent4 = (blobTo / totalSize).toFixed(3) * 1;
var percent5 = (blobTo / totalSize).toFixed(3) * 10; console.log(percent1, typeof(percent1)); // 0.9439375747533572 "number"
console.log(percent2, typeof(percent2)); // 0.944 string
console.log(percent3, typeof(percent3)); // 94.39999999999999 "number"
console.log(percent4, typeof(percent4)); // 0.944 "number"
console.log(percent5, typeof(percent5)); // 9.44 "number"
好生奇怪... 乘以10正常,当乘以100时,好像失真了
不明觉厉
最后找到一种方法解决,在括号里面先乘上100
var percent = (100* blobTo / totalSize).toFixed(1); percent // 94.4
还不知道具体是为啥这样,知道的可以告诉我哈~