Javascript数字分度

时间:2019-05-03 07:12:27

标签: javascript node.js aws-lambda

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

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

这是我使用的逻辑:

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

4 个答案:

答案 0 :(得分: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))

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

在结果上使用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)并丢弃最后一位。

答案 3 :(得分:0)

如果我正确理解,您的目标是返回格式正确的字符串作为除法的输出,而不管结果是否为整数。

为什么不将2个输入解析为数字,进行除法,然后格式化输出以使其符合您的需要?

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 = totalPriceFloat / runningTimeNumber; // I do not need rounding. Need exact decimals

    return result.toFixed(2) // returns a string with 2 digits after comma
}