toFixed |
toFixedと浮動小数誤差 |
//[test1]
console.log( (1.234).toFixed(2) );//1.23
console.log( (1.235).toFixed(2) );//1.24
console.log( (1.245).toFixed(2) );//1.25
console.log( (1.255).toFixed(2) );//1.25
console.log( (1.005).toFixed(2) );//1.00
//[test2]
function roundTo(value, digits = 0)
{
const factor = 10 ** digits;
const shifted = Number((value * factor).toFixed(12));
return Math.round(shifted) / factor;
}
console.log(roundTo(1.005, 2)); //1.01
console.log(roundTo(1.335, 2)); //1.34
console.log(roundTo(1234.567, 0));//1235
console.log(roundTo(-1.005, 2)); //-1
//[test3]
function roundToSafe(value, digits = 0)
{
const factor = Math.pow(10, digits);
return Math.round((value + Number.EPSILON) * factor) / factor;
}
console.log(roundToSafe(1.005, 2)); //1.01
console.log(roundToSafe(1.235, 2)); //1.24
| ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。 ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、 または公開したりすることはできません。 当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、 その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について 一切の責任を負わないものとします。 |