Tuesday 19 July 2016

Decimal indicator comma instead of dot. Number fix using JavaScript.

We recently had an issue where a customer was complaining that our website does not accept commas as decimal indicators on a certain page. Which is fair, it was never written to accept commas. but what if regional settings changes an unknowing users way of interacting with our system?

First I tried to replicate the issue by changing my decimal indicator using the steps below:

This method is tested on Windows 8.1.

1. Press WIN (windows key) + X

2 Select Control Panel


3 Select Change date, time, or number formats from the Clock, Language, and Region item (Note: If you can't see the icons, change View By to Category)







4. Click Additional settings...















5. Change Decimal symbol to a comma (,) and press Apply and OK



When you navigate to a field which contains a number with decimal places, the decimal symbol should change from a dot (.) to a comma (,) I tested this using IE as the browser.

Our website's convention dictates that we allow 2 decimal places denoted by a dot(.). But our users are not able to interact with our system due to regional settings and that can't be allowed.

My Solution: 


Given the case, users are allowed to enter numbers that are:
  • Thousand separated by commas, decimals denoted by a dot.
  • Not thousand separated, decimals denoted by a comma.
  • Not thousand separated, no decimals.

I fixed this issue using JavaScript, which is also how this specific page's numbers get saved.

All you need is a small function that uses regex to check for commas:

function TranslateValues(item) {
  var Splitting = item.indexOf(",") != -1 ? item.split(',')[1].length : 0;
  var newItem = Splitting == 2 ? item.replace(/,/g, ".") : item.replace(/,/g, "");
  alert(newItem);
}

To cover all bases, I created a more thorough example that loops through a variety of numbers and writes the value to a paragraph. You can find that example by clicking here

No comments:

Post a Comment