In my program, the user enters values betweeen 0 and 8.
For example: if the user wants to input “3,4” he only needs to write “34”. the program will eventually put the comma in, but I have no clue how to do it.
So:
input = “34” –> output = “3,4”
input = “09” –> output = “0,9”
This is what i tried, but of course it will accept “34” as integer:
function numberWithCommas(x) {
return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
}
I also tried to split the input, but when the user inputs a integer like 3, it doesn’t work anymore.
There’s no deeper meaning to this problem, but to make the user input faster.
Advertisement
Answer
You should:
- Convert the input number to a string (
toString); - Split the string between each character into an array (
split); - Join the elements of this array, separated by
,(join).
Here you are the full code:
function numberWithCommas(x) {
return x.toString().split("").join(",");
}