Objective

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

Difficulty

Easy

Description

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

Let's recall its syntax:

number.toPrecision(precision)

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'
58 .toPrecision(3)
'58.0'
124 .toPrecision(3)
'124'
124 .toPrecision(4)
'124.0'

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)
'1e+2'
124 .toPrecision(2)
'1.2e+2'
178 .toPrecision(2)
'1.8e+2'
17000 .toPrecision(1)
'2e+4'
17000 .toPrecision(2)
'1.7e+4'
17000 .toPrecision(3)
'1.70e+4'
389520 .toPrecision(4)
'3.895e+5'

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)
'100'
betterPrecision(124, 2)
'120'
betterPrecision(178, 2)
'180'
betterPrecision(17000, 1)
'20000'
betterPrecision(17000, 2)
'17000'
betterPrecision(17000, 3)
'17000'
betterPrecision(389520, 4)
'3.895e+5'

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'.

Hints