猿问

Javascript数字分度

除数时,我需要处理几种情况。


规则: -除法必须始终返回小数点后两位-不能四舍五入。


这是我使用的逻辑:


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。数字来自数据库,并且最初始终是字符串。


阿晨1998
浏览 127回答 3
3回答

天涯尽头无女友

推荐的策略是先将数字乘以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))

HUH函数

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

跃然一笑

您可以尝试toFixed(2)在结果行中添加:result = (totalPriceFloat / runningTimeNumber).toFixed(2);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答