Replace with Split in JavaScript to Append 0 for Single Digit After Comma



Let’s say our sample string is −

const a = "250,5";

If the number after “,” is a single digit we have to append a 0 to it,

If the string contains more than one ‘,’, we have to return -1

This can be done simply by combining the split() and replace() functions like this as in the below example −

Example

const a = "250,5";
const roundString = (str) => {
   if(str.split(",").length > 2){
      return -1;
   }
   return a.replace(`,${a.split(",")[1]}`, `,${a.split(",")[1]}0`);;
}
console.log(roundString(a));

Output

The console output for this code will be −

250,50
Updated on: 2020-08-18T07:10:23+05:30

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements