I have a problem. Script parsing csv to html. But number is read as a string. How can I add "0" to numbers that do not have to decimals. For example:
15,45
12,00
14,2
14,54
I want to add 0 to all numbers like 4,2
15,45
12,00
14,20
14,54
Try
var output = "15,2".split(",").map(function(val){ return val > 100 ? val: (val+"00").slice(0,2);}).join(",");
alert(output);
var output = "15,100".split(",").map(function(val){ return val > 99 ? val: (val+"00").slice(0,2);}).join(",");
alert(output);
var output = "15,".split(",").map(function(val){ return val > 100 ? val: (val+"00").slice(0,2);}).join(",");
alert(output);
15,15 it outputted me 15,15 what should be the output in this case?15, should output 15.00In vanillaJS
var num = "14,2";
/* string to number conversion */
num = +(num.replace(',','.'));
/* set 2 digits after decimal point */
num = num.toFixed(2);
/*
Input Output
--------------
14,25 14.25
14,2 14.20
14 14.00 */
Reduced in a single statement, as suggested in the comments below:
(+num.replace(',','.')).toFixed(2);
if you have an array of strings you could easily convert them using Array.map()
var nums = ["14", "14,2", "14,25"];
nums = nums.map(n => (+n.replace(',','.')).toFixed(2));
// => ["14.00", "14.20", "14.25"]
(+num.replace(',','.')).toFixed(2); ?
12,00is different from12.00What do you expect exactly?