3 回答

TA贡献1831条经验 获得超9个赞
推荐的策略是先将数字乘以100(如果您要求小数点后3位,然后是1000,依此类推)。将结果转换为整数,然后除以100。
function divideAndReturn (totalPrice, runningTime) {
let result;
let totalPriceFloat = parseFloat(totalPrice); // no need to format anything right now
let runningTimeNumber = parseInt(runningTime, 10); // Always a round number
result = parseInt((totalPriceFloat * 100) / runningTimeNumber); // I do not need rounding. Need exact decimals
result /= 100
return result.toFixed(2) // returns a string with 2 digits after comma
}
console.log(divideAndReturn('1000.00', 6))
console.log(divideAndReturn('100.00', 12))
console.log(divideAndReturn('1000.00', 5))

TA贡献1836条经验 获得超4个赞
用于toFixed结果以将数字转换为所需格式的字符串。将整数转换为字符串将永远不会呈现和小数点后的数字。
function divideAndReturn (totalPrice, runningTime) {
let totalPriceFloat = parseFloat(totalPrice);
let runningTimeNumber = parseInt(runningTime, 10);
let result = totalPriceFloat / runningTimeNumber;
// without rounding result
let ret = result.toFixed(3)
return ret.substr(0, ret.length-1);
}
console.log(divideAndReturn('1000.00', '6'))
console.log(divideAndReturn('100.00', '12'))
console.log(divideAndReturn('1000.00', '5'))
要删除任何“舍入”,请使用toFixed(3)
并舍弃最后一位数字。

TA贡献1826条经验 获得超6个赞
您可以尝试toFixed(2)
在结果行中添加:
result = (totalPriceFloat / runningTimeNumber).toFixed(2);
添加回答
举报