Replace() with Split() in JavaScript to append 0 if number after comma is a single digit

When working with decimal numbers as strings, you often need to format them properly. This article shows how to append a zero to single-digit numbers after a comma using JavaScript's split() and replace() methods.

Problem Statement

Given a string like "250,5", we need to:

  • Append a zero if the number after the comma is a single digit
  • Return -1 if the string contains more than one comma

Solution Using split() and replace()

We can combine split() and replace() methods to achieve this:

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

How It Works

The function works in two steps:

  1. Validation: str.split(",").length > 2 checks if there are more than one comma
  2. Replacement: replace() finds the decimal part and appends a zero

Testing Multiple Cases

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

console.log(roundString("250,5"));     // Single digit after comma
console.log(roundString("100,25"));    // Two digits after comma  
console.log(roundString("50,1,2"));    // Multiple commas
console.log(roundString("75,0"));      // Zero after comma
250,50
100,250
-1
75,00

Improved Version

Here's an optimized version that splits only once:

const roundString = (str) => {
    const parts = str.split(",");
    if(parts.length > 2){
        return -1;
    }
    return `${parts[0]},${parts[1]}0`;
}

console.log(roundString("250,5"));
console.log(roundString("100,25"));
console.log(roundString("50,1,2"));
250,50
100,250
-1

Key Points

  • split(",") divides the string into an array at each comma
  • replace() substitutes the decimal part with the same part plus "0"
  • The length check prevents processing strings with multiple commas
  • The improved version is more efficient by splitting only once

Conclusion

Combining split() and replace() provides an effective way to format decimal strings. The key is validating the input structure before applying the transformation.

Updated on: 2026-03-15T23:18:59+05:30

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements