0

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
2

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

3 Comments

@fcalderan for 15,15 it outputted me 15,15 what should be the output in this case?
try with 15, should output 15.00
@fcalderan it will now, please check
2

In 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"]

2 Comments

This is the most correct and most performant answer. Maybe compete with the one-liners and write it like this: (+num.replace(',','.')).toFixed(2); ?
yes, but for clarity purpose I splitted the code in two readable (and commented) lines, I'm not doing a codegolf competition :)
1

If you get all strings as posted format in the OP you could use length :

["15,45","12,00","14,2"].forEach(function(v){
    alert(v.split(',')[1].length==1?v+"0":v);
})

Comments

0

You can use this:

var arr = ["15,45","12,00","14,2","14,54"];

var newarr = arr.map(function(o){
  var val = o.split(',');
  return val[1].length == 1 ? val.join(',')+"0" : val.join(',');
});

document.querySelector('pre').innerHTML = JSON.stringify(newarr, 0, 4);
<pre></pre>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.