为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript数字分度

Javascript数字分度

阿晨1998 2021-05-07 18:12:55
除数时,我需要处理几种情况。规则: -除法必须始终返回小数点后两位-不能四舍五入。这是我使用的逻辑:function divideAndReturn (totalPrice, runningTime) {  let result;  let totalPriceFloat = parseFloat(totalPrice).toFixed(2);  let runningTimeNumber = parseInt(runningTime, 10); // Always a round number  result = totalPriceFloat / runningTimeNumber; // I do not need rounding. Need exact decimals  return result.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]; // Preserve only two decimals, avoiding rounding up.}在以下情况下,它可以正常工作:let totalPrice = '1000.00';let runningTime = '6';// result is 166.66它也适用于这种情况:let totalPrice = '100.00';let runningTime = '12';// Returns 8.33但是对于这种情况,它不能按预期工作:let totalPrice = '1000.00';let runningTime = '5';// Returns 200. Expected is 200.00看来,当我对舍入数字进行除法时,除法本身删除了.00小数位如果我的逻辑可以解决,请说明一下。或者,如果有更好的方法来弥补这一点,我也很高兴。PS。数字来自数据库,并且最初始终是字符串。
查看完整描述

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))


查看完整回答
反对 回复 2021-05-20
?
HUH函数

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)并舍弃最后一位数字。


查看完整回答
反对 回复 2021-05-20
?
跃然一笑

TA贡献1826条经验 获得超6个赞

您可以尝试toFixed(2)在结果行中添加:

result = (totalPriceFloat / runningTimeNumber).toFixed(2);


查看完整回答
反对 回复 2021-05-20
  • 3 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信