My current project involves iterating through an array of floating point numbers. The goal is to format each float to a specific pattern ".XXX" where X represents a number. If the float begins with a 0, it should be excluded. For instance, 0.2867
should appear as .286
, while 1.2
should become 1.200
. In case an element in the array is not a number like "-", it should be displayed as .000
.
I have shared my code for this task below but I seem to be stuck:
$( document ).ready(function() {
var statsArray = [0.2867, 0.833, 1.576, 0.19, 0.688, 0.22, 0.572, .167, 0.643, 0.921, "-", "-", 0.222, 1.466789, 0.1, 0.714, 1.115];
function formatter()
{
var numElements = statsArray.length;
for (var m=0; m <= numElements; m++)
{
var arrayElement = statsArray[m];
console.log ("original element is " + arrayElement);
arrayElement = parseInt(arrayElement, 10);
console.log ("after parseInt element is " + arrayElement);
arrayElement = arrayElement.toPrecision(3);
console.log ("after toPrecision element is " + arrayElement);
}
}
formatter();
});
I would appreciate any suggestions on how to proceed or if there are any gaps in my approach! Thank you!