Sitemap
Full Stack Web Development

Learning how to build powerful web apps

Practice comparing numbers with toFixed(), toExponential(), toPrecision()

1 min readDec 27, 2016

--

Use the above functions to perform the task below

Task

Create a function howManySmaller(). The function accepts 2 parameters, arrarr and n. arris a decimal array. n is a decimal.

The first mission: let all elements in the array keep two decimal places(No need to convert number n).

The second mission: Traverse arr, count the number of the elements which are smaller than n and return it.

Get Isaac Pak’s stories in your inbox

Join Medium for free to get updates from this writer.

for example:

howManySmaller([1.234,1.235,1.228],1.24) should return 2
howManySmaller([1.1888,1.1868,1.1838],1.19) should return 1
howManySmaller([3.1288,3.1212,3.1205],3.1212) should return 2

Simple Solution:

function smaller(arr, n) {
var count = 0;
var fixed = arr.map(function(x) {
return x.toFixed(2);
});
for(var i=0; i < fixed.length;i++) {
if(+fixed[i]<n) {
count++;
};
};
return count;
};

smaller([1.234,1.235,1.228],1.24);

Elegant Solution:

function howManySmaller(arr,n){ return arr.filter(x => +x.toFixed(2) < n).length; }

This is an excerpt from codewars. A great place to become a better coder.

--

--