javascriptfunctiontofixed

Making a thousands (k) convertor function in Javascript without rounding and NOT remove .0 from end


I am trying to make a simple 1000 to k convertor function in JS that will take a number and convert it into thousands/k. I'm having trouble getting the .toFixed(1) working properly. I don't want it to round up and I want it to show one decimal place UNLESS that decimal is a 0. A few examples of the returns I am looking to produce are:

1100 -> 1.1K

1199 -> 1.1K

9999 -> 9.9K

10900 -> 10.9K

10999 -> 10.9K

JS

   function kConvertor(num) {
     return num <= 999 ? num : (num/1000).toFixed(1) + 'k'
    }

This returns 10.0k which hits both cases that I do not want (9.9k). What am I doing wrong here?

I tried adding a parseInt() and .replace('.0', '') to the end and that didn't work.

   function kConvertor(num) {
      return num <= 999 ? num : parseInt((num/1000)).toFixed(1).replace('.0', '') + 'k'
   }

This just returns 9k


Solution

  • This works by using math operators to correctly round down to the nearest 10th of a K, and then uses .toFixed(1) to perform the string manipulation necessary to strip .0 from the result:

    function kConverter(num) {
        return num <= 999 ? num : (0.1 * Math.floor(num / 100)).toFixed(1).replace('.0','') + 'k'
    }
    

    NB: it's not good practise to have the function return a number for <= 999, or a string otherwise. Unexpected result types is the cause of the vast majority of the "WAT?!" moments from the famous video. Always ensure that your return types are consistent:

    function kConverter(num) {
        if (num < 1000) {
            return number.toFixed(0);   // assuming an integer
        } else {
            const s = (0.1 * Math.floor(num / 100)).toFixed(1);
            return s.replace('.0', '') + 'k';
        }
    }