Reputation: 16494
I get numbers from 1 to 5 including all possible floating point numbers in between. The output must contain two digits after comma and in case of after-comma digits they need to be rounded down (floor).
Example input and output:
My try is doing a Math.floor on the 100x of the number and dividing afterwards to get rid of the unwanted digits after comma. The Number.toFixed(2) gets me the possibly missing zeros afterwards:
(Math.floor(input * 100) / 100).toFixed(2)
The problem with this is JavaScript's floating point inprecision:
Math.floor(4.14 * 100) / 100
// results in 4.13 because 4.14 * 100 is 413.99999999999994
Upvotes: 1
Views: 1686
Reputation: 5348
function formatNumber(x) {
// convert it to a string
var s = "" + x;
// if x is integer, the point is missing, so add it
if (s.indexOf(".") == -1) {
s += ".";
}
// make sure if we have at least 2 decimals
s += "00";
// get the first 2 decimals
return s.substring(0, s.indexOf(".") + 3);
}
document.write(1 + " -> " + formatNumber(1) + "<br/>");
document.write(4.3 + " -> " + formatNumber(4.3) + "<br/>");
document.write(1.1000 + " -> " + formatNumber(1.1000) + "<br/>");
document.write(1.5999 + " -> " + formatNumber(1.5999) + "<br/>");
document.write(4.14 + " -> " + formatNumber(4.14) + "<br/>");
Here is my attempt, the idea is documented in the code. Of course, there are probably better solutions, but this is a quick & dirty solution.
Upvotes: 2