Округление до следующего целого числа javascript - PullRequest
2 голосов
/ 01 апреля 2020

Я хочу добиться чего-то подобного в JavaScript:

input = 2455.55
f(input) = 2456
f(input) = 2460
f(input) = 2500
f(input) = 3000
f(input) = 2455.55

Сейчас я использую метод Math.round(), но получаю только 2,546 с ним. Хотите знать, есть ли лучший способ достичь отдыха?

Ответы [ 3 ]

3 голосов
/ 01 апреля 2020

Вы можете делить свое число на десять до тех пор, пока не получите нецелое число, округлите его и затем умножьте на десять снова столько же времени. Как то так:

    function roundUp(n) {
    
        var n2 = n;
        var i=0;
        while (Number.isInteger(n2)) {
      	    n2 /= 10;
            i++;
        }
        return Math.round(n2) * Math.pow(10, i);
    
    }

    console.log(roundUp(2455.55)); // 2456
    console.log(roundUp(2456)); // 2460
    console.log(roundUp(2460)); // 2500
    console.log(roundUp(2500)); // 3000
1 голос
/ 10 апреля 2020

Исходя из вашего желаемого результата, похоже, что вам нужно отслеживать количество вызовов функций. Это не похоже на аргумент вашей функции.

Учитывая ограничение, что у вас есть только один аргумент, реализация, вероятно, выглядит как

var lastNum = 0
var digitsToRound = 0

function roundUp(input) {
  // Verify whether the function is called with the same argument as last call.
  // Note that we cannot compare floating point numbers.
  // See https://dev.to/alldanielscott/how-to-compare-numbers-correctly-in-javascript-1l4i
  if (Math.abs(input - lastNum) < Number.EPSILON) {
    // If the number of digitsToRound exceeds the number of digits in the input we want
    // to reset the number of digitsToRound. Otherwise we increase the digitsToRound.
    if (digitsToRound > (Math.log10(input) - 1)) {
      digitsToRound = 0;
    } else {
      digitsToRound = digitsToRound + 1;
    }
  } else {
    // The function was called with a new input, we reset the digitsToRound
    digitsToRound = 0;
    lastNum = input;
  }

  // Compute the factor by which we need to divide and multiply to round the input
  // as desired.
  var factor = Math.max(1, Math.pow(10, digitsToRound));
  return Math.ceil(input / factor) * factor;
}


console.log(roundUp(2455.55)); // 2456
console.log(roundUp(2455.55)); // 2460
console.log(roundUp(2455.55)); // 2500
console.log(roundUp(2455.55)); // 3000
0 голосов
/ 01 апреля 2020

спасибо, хороший! Вдохновленный вашим ответом, я решил это так:

function roundNumber(num, n) {
  const divider = Math.pow(10, n);
  return Math.round(num / divider) * divider;
};
...