How to convert a string with zeros to number in JavaScript?

When you have a string containing numbers with dots or zeros as separators, you can convert it to a number using JavaScript's built-in methods. This is commonly needed when processing formatted numeric data.

The Problem

Consider a string like "453.000.00.00.0000" where dots are used as thousand separators rather than decimal points. Direct conversion methods like Number() won't work correctly because JavaScript interprets the first dot as a decimal separator.

let stringValue = "453.000.00.00.0000";
console.log("Original string:", stringValue);
console.log("Direct Number() conversion:", Number(stringValue)); // NaN
Original string: 453.000.00.00.0000
Direct Number() conversion: NaN

Using parseInt() with replace()

The most effective approach is to remove all dots using replace() with a regular expression, then convert the cleaned string to a number using parseInt().

let stringValue = "453.000.00.00.0000";
let numberValue = parseInt(stringValue.replace(/\./g, ''));

console.log("Original value:", stringValue);
console.log("After conversion:", numberValue);
console.log("Type check:", typeof numberValue);
Original value: 453.000.00.00.0000
After conversion: 45300000000000
Type check: number

Alternative Methods

You can also use Number() after cleaning the string, or handle different separators:

let stringValue = "453.000.00.00.0000";

// Method 1: Using Number()
let method1 = Number(stringValue.replace(/\./g, ''));

// Method 2: Handle multiple separators
let stringWithCommas = "1,234,567.89";
let method2 = parseFloat(stringWithCommas.replace(/,/g, ''));

console.log("Method 1 result:", method1);
console.log("Method 2 result:", method2);
Method 1 result: 45300000000000
Method 2 result: 1234567.89

Regular Expression Breakdown

The regular expression /\./g works as follows:

  • \. - Matches literal dot characters (escaped because dot is a special regex character)
  • g - Global flag to replace all occurrences, not just the first one

Handling Edge Cases

// Empty or invalid strings
console.log("Empty string:", parseInt("".replace(/\./g, '')) || 0);
console.log("Only dots:", parseInt("...".replace(/\./g, '')) || 0);

// Leading zeros
let withLeadingZeros = "000123.456.789";
console.log("With leading zeros:", parseInt(withLeadingZeros.replace(/\./g, '')));
Empty string: 0
Only dots: 0
With leading zeros: 123456789

Conclusion

Use parseInt() with replace(/\./g, '') to convert dot-separated numeric strings to numbers. This method effectively removes separator characters and converts the result to an integer, handling most formatting scenarios you'll encounter.

Updated on: 2026-03-15T23:19:00+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements