function formatUpToANumberOfZeroesAfterFloatingPoint(number, numberOfZeroes, floatingPointSymbol) {
    numberOfZeroes = (numberOfZeroes === undefined || numberOfZeroes < 0) ? 2 : numberOfZeroes;
    floatingPointSymbol = floatingPointSymbol === undefined ? '.' : floatingPointSymbol;
    let numberSplitByFloatingPoint = number.toString().split(floatingPointSymbol);
    if (numberSplitByFloatingPoint.length !== 2) 
        return `${number}${floatingPointSymbol}${'0'.repeat(+numberOfZeroes)}`;
    
    let numberAfterFloatingPoint = numberSplitByFloatingPoint[1].toString();
    let formattedNumber = `${numberSplitByFloatingPoint[0]}`;
    let numberAfterFloatingPointLength = numberAfterFloatingPoint.toString().length;
    if (+numberOfZeroes > +numberAfterFloatingPointLength) 
        return `${formattedNumber}${floatingPointSymbol}${numberAfterFloatingPoint}${'0'.repeat(+numberOfZeroes - numberAfterFloatingPointLength)}`;
    
    let countOfNumbersAfterFloatingPoint = numberAfterFloatingPointLength;
    for (var i = numberAfterFloatingPointLength - 1; i >= 0; i--) {
        if (+(numberAfterFloatingPoint[i]) !== 0 || +countOfNumbersAfterFloatingPoint === +numberOfZeroes) {
            formattedNumber += `${floatingPointSymbol}${numberAfterFloatingPoint.substring(0, countOfNumbersAfterFloatingPoint)}`;
            break;
        }
        
        countOfNumbersAfterFloatingPoint--;
    }

    return formattedNumber;
}

Well, a junior dev here. A cute female QA came to me with a request - "the field for the price already has precision up to 4 decimal places, but we don't like the 4 ugly zeroes, so if the number ends in zeroes, let it have only 2" - she said in the most innocent-like tone ever known to mankind. How easy I mumbled and accepted the task. As she was leaving she added - "oo almost forgot, we also would like it if all the data fields for the price that are shown in the tables also are formatted that way". As I was watching her better side, while she was getting reunited with her QA tribe, I got shivers down the spine. I had a bad feeling about that one, but I wasn't sure why yet. Suddenly as I was getting up to get a cup of coffe, it dawned on me - "this poor excuse for a project is using jqGrid for displaying the data". To wrap things up - I got a quadruple espresso with a shot of Jacky, developers best friend in a time of need, and came up with this piece of art. Enjoy :)

By Kristopher Alexander, 2019-04-25 15:49:53