Create a function that extends the number method toPrecision() to return a stringified number without exponential notation when the exponent is less than 5.




In the last chapter on JavaScript Number Methods, we saw the toPrecision() method.

Let's recall its syntax:


It takes an argument precision and rounds a given number to the specified significant figure precision.

Shown below are a couple of examples of the method.

58 .toPrecision(2)
58 .toPrecision(3)
124 .toPrecision(3)
124 .toPrecision(4)

In the chapter, we also saw that toPrecision() has a special return value when the argument passed to it is less than the number of digits in number's integer part. That is, it returns the stringified number in exponential notation.

Consider the snippet below:

124 .toPrecision(1)
124 .toPrecision(2)
178 .toPrecision(2)
17000 .toPrecision(1)
17000 .toPrecision(2)
17000 .toPrecision(3)
389520 .toPrecision(4)

In the first statement, you might expect the return value to be '100', however this isn't the case. Instead, '1e+2' is returned.

As you would agree, for small numbers, like 100, this behavior of toPrecision() could be redundant and undesirable.

In this exercise, you have to create a function called betterPrecision() that solves this problem.

The function takes in two args, num and precision, as demonstrated in the partial definition below:

function betterPrecision(num, precision) {
   // code goes here

The return value of this function is exactly the same value returned by num.toPrecision(precision), except for when it is in exponential notation and is otherwise easily representable in normal decimal notation.

If the exponent is less than 5, the number could be represented easily in decimal notation.

Shown below are some examples of the function (that you'll be creating) on the values for which toPrecision() returns stringified numbers in exponential notation.

betterPrecision(124, 1)
betterPrecision(124, 2)
betterPrecision(178, 2)
betterPrecision(17000, 1)
betterPrecision(17000, 2)
betterPrecision(17000, 3)
betterPrecision(389520, 4)

In the last statement, since the exponent is not less than 5, the value returned by num.toPrecision(precision) is returned as is by betterPrecision() i.e, '3.895e+5'.