function roundNumericWithPlaces()

in ui-modules/utils/utils/general.js [91:124]


function roundNumericWithPlaces(n, maxDecimalDigits, minDecimalDigits, onlyCountSignificantDecimalDigits, countNines) {
    maxDecimalDigits = maxDecimalDigits || 0;
    minDecimalDigits = minDecimalDigits || 0;
    if (countNines) n = 1-n;

    // one recommended way to round; but seems inefficient using strings, causes round(0.499, 2) to show 0.5 not 0.50, and doesn't deal with significant decimal digits
    // return Number(Math.round(Number(''+n+'e'+maxDecimalDigits))+'e-'+maxDecimalDigits);

    let placesToShow = 0;
    let significantPlaces = 0;
    for (;;) {
        if (isInteger(n)) break;
        n *= 10;
        if (onlyCountSignificantDecimalDigits && !significantPlaces) {
            if (isEqualWithinTolerance(n, 0, 1)) {
                // accept an extra digit if we are still dealing with insignificant digits
                significantPlaces--;
            }
        }
        significantPlaces++;
        placesToShow++;
        if (significantPlaces >= maxDecimalDigits && significantPlaces>0 && placesToShow>=minDecimalDigits) break;
    }
    let nr = Math.round(n);
    if (!maxDecimalDigits && placesToShow > significantPlaces) {
        // if no decimal digits but significant places then keep the right number of zeroes/ones
        nr = Math.round(nr/10);
        placesToShow--;
    }
    let i = placesToShow;
    while (i-->0) nr/=10;
    if (countNines) nr = 1-nr;
    return [nr, Math.max(placesToShow, minDecimalDigits)];
}