Click here to Skip to main content
Click here to Skip to main content

Add Delimiters to Numbers in JavaScript Using Regex

, 1 Feb 2014
Rate this:
Please Sign up or sign in to vote.
Use regular expression to add user-defined delimiters to numbers in JavaScript

Introduction

Unlike its counterparts, there is no native method in JavaScript to add delimiters such as commas to numbers. In this article, we shall explore and discuss the use of regex to achieve this objective.

Using the Code

This is a one-page HTML file. Copy and save it to a text file, say "demo.html". Launch it on any web browser to test it (Figure 1). 

<!DOCTYPE html>
<html>
<head>
  <title>Number Add Delimiters to Numbers in JavaScript Using Regex by Peter Leow @2014</title>
  <script>
  function getFormattedNumber()
  {
     var number = document.getElementById("rawNumber").value;
     var decimal= document.getElementById("decimalPlaces").value;
     var delimiter= document.getElementById("delimiter").value;
     var result = formatNumber(number, decimal, delimiter);
     document.getElementById("result").value=result;
  }
  function formatNumber(rawNumber, decimal, delimiter) 
  {
     var temp = parseFloat(rawNumber).toFixed(decimal);
     var partArray = temp.toString().split("."); 
     partArray[0] = partArray[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, delimiter); 
     return partArray.join("."); 
  } 
  </script>  
  <style type="text/css"> 
  body { 
  background-color: #0FF; 
  } 
  table { 
  border-spacing:10px 10px; 
  } 
  td#label { 
  text-align:right; 
  } 
  </style> 
</head> 
<body> 
  <table> 
  <caption> 
  Add Delimiters to Numbers 
  </caption> 
  <tr> 
  <td id="label" width="32%">Number String : </td> 
  <td width="68%"><input type="text" 
  name="rawNumber" id="rawNumber"></td> 
  </tr> 
  <tr> 
  <td id="label" >Desired Decimal Places : </td> 
  <td><input type="text" name="decimalPlaces" 
  id="decimalPlaces"></td> 
  </tr> 
  <tr> 
  <td id="label" >Desired Delimiter : </td> 
  <td><input type="text" name="delimiter" 
  id="delimiter"></td> 
  </tr> 
  <tr> 
  <td>&nbsp;</td> 
  <td><button onclick="getFormattedNumber()">Format Now
  </button></td>

  </tr> 
  <tr> 
  <td id="label">Result : </td> 
  <td><input type="text" name="result" 
  id="result"></td>

  </tr> 
  </table> 
  <br>  
</body> 
</html> 

Screen shot

Figure 1 - Screenshot

Points of Discussion

We will focus our discussion on the JavaScript function of 'formatNumber()' with reference to the example shown on the screenshot of Figure 1.

 function formatNumber(rawNumber, decimal, delimiter) 
 {
     var temp = parseFloat(rawNumber).toFixed(decimal);
     var partArray = temp.toString().split("."); 
     partArray[0] = partArray[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, delimiter); 
     return partArray.join("."); 
} 

Point 1 - Since the addition of delimiters only concerns the whole number part of the number string, we shall split the number string into the whole number part and decimal number part, i.e. "123456789" and ".4326".

Point 2 - In plain natural language, we may say, "Start from the right most position of the whole number, find the first 3-digit block, add a delimiter to the left boundary of this block; next, start from the right most position of the whole number again, find the first 6-digit block, add a delimiter to the left boundary of this block. Repeat the process, but this time find the first 9-digit block and so on. This repetition will end with no addition of delimiter when the left boundary of a new block is the left boundary of the whole number or it fails to find any new block."

To translate this into regex, we have: \B(?=(\d{3})+(?!\d))

Point 3 - Let's dissect this regex pattern and study its elements:

\B

Match a position that is NOT the beginning or the end of a word.

(expression)

Match and capture the expression in a numbered group.

(?=expression)

Match any position that is followed by the expression.

\d

Match any single digit.

{n}

Repeat n times for the preceding element.

+

Repeat one or more times for the preceding element.

(?!expression)

Match any position that is NOT followed by the expression.

Point 4 - Armed with the knowledge from Point 3, we can now analyse the regex pattern in Point 2.

(?=(\d{3})+)

Match any position that is followed by one or more 3-digit blocks. Accordingly, the candidate positions include the left boundaries of 123, 234, 345, 456, 567, 678, and 789 respectively.

Using this regex, the result of adding delimiter of commas will be ,1,2,3,4,5,6,789

(?!\d)

Match the position that is NOT followed by a single digit. Accordingly, only the right boundary of 123456789 meets this criterion. So the result of using this regex alone will be 123456789,

(?=(\d{3})+(?!\d))

Combine them together, it will match any position that is followed by one or more 3-digit blocks which in turn is NOT followed by any single digit. This has effectively narrowed the candidate positions down to the left boundaries of 789 (one 3-digit block), 456789 (two 3-digit blocks), and 123456789 (three 3-digit blocks).

If we stop here, then the result of adding delimiter of commas will be ,123,456,789

\B(?=(\d{3})+(?!\d))

Adding \B to the regex will EXCLUDE any position that is the beginning or the end of a word, in other words, it excludes the left most comma from the previous result and we get what we want, i.e. 123,456,789

Point 5 - The last part is just to append the decimal number back to the comma-delimited whole number and we are done.

History

  • First edition: 01 February 2014

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Peter Leow
Instructor / Trainer
Singapore Singapore
Graduated from the National University of Singapore with the following qualifications:
1. Graduate Diploma in Systems Analysis (2002)
2. Master of Technology (Knowledge Engineering) (2013)
 
Currently, lecturing in the area of social media and web development at a technical institution.
 
Having hibernated for ages, finally woke up to serve the Community in Oct 2013.
Follow on   LinkedIn

Comments and Discussions

 
GeneralNice Article with good Explanation PinmemberMember 42975244-Feb-14 1:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140718.1 | Last Updated 1 Feb 2014
Article Copyright 2014 by Peter Leow
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid