matrixfox
matrixfox

Reputation: 83

Rounding a value using fixed decimal places

I have a numerical input, 'value' that is getting floored when I input a value with decimal places exceeding my parameter amount (5).

For example, if I enter 1.99999 it works when I exit the cell. If I enter 1.999999 (6 decimals), it floors down to 1.00000.

    let integralPart = Math.floor(value);
    let fractionalPart = (value - integralPart);
    let result: string[] = [];
    let s = String(integralPart);

I'm trying to include an if statement to correct this bug

    if (fractionalPart.length > decimalPlaces) {
        to.fix(decimalplaces)
    }

Currently I get the error that says 'property length does not exist on type number'. Anyone have any suggestions? Fairly new to TS.

Upvotes: 0

Views: 1008

Answers (1)

brunnerh
brunnerh

Reputation: 185225

Not quite sure what you are trying to achieve there. If you just want to round a value with fixed digits there are various ways of doing it.

If you want a string output:

const digits = 5;
const toFixed = x => x.toLocaleString(undefined, {
  minimumFractionDigits: digits,
  maximumFractionDigits: digits
});

console.log(toFixed(1.99999));
console.log(toFixed(1.999999));

If you just want the number to not exceed a given precision:

const digits = 5;
const shift = Math.pow(10, digits);
const round = x => {
  return Math.round(x * shift) / shift;
};

console.log(round(1.99999));
console.log(round(1.999999));

Upvotes: 2

Related Questions