FORMAT CURRENCY FIELD WITH JAVASCRIPT PART 2

In the beginning if the year I wrote the first part of this currency field formatter that we have on our application without knowing it would have a second part.

Here it is refactored after 5 months

function integerFieldFormatter(number) {
  number = number.replace(',', '.');
  number = Math.round(Number(number)).toString();
  if (number === '0' || number === 'NaN') {
    return '';
  } else {
    return number;
  }
}

function decimalFieldFormatter(number) {
  if (number === '') {
    return number;
  } else {
    var splitted_number = number.split(/[\,.]/g);
    if (splitted_number.length > 2) {
      decimal_numbers = splitted_number.pop();
      whole_numbers = splitted_number.join('');
      number = whole_numbers.concat('.' + decimal_numbers);
      number = parseFloat(number).toFixed(2);
    } else {
      number = number.replace(',', '.');
      number = parseFloat(number).toFixed(2);
    }
    number = number.replace('.', ',');
    return number;
  }
}

var formatCurrency = function(element) {
  $this = $(element);
  var value = $this.val();

  value = value.replace(/[^0-9,.]/g, '');

  if ($this.attr('only_integer')) {
    value = integerFieldFormatter(value);
  } else {
    value = decimalFieldFormatter(value);
  }

  $this.val(value);
  $this.next().val(value.replace(/[\,]/g, '.'));
};

When we were adding more functionality to our app I came across a bug. The code would only return a positive value and we had fields that accepted negative values and this was something I tackled right away.

This value = value.replace(/[^0-9,.]/g, ”); would replace everything but commas, dots and numbers.
To be honest I spent about tWo hours to find a regex that would replace the dashes after the first.

If the value was -1234,5– it would remove the last 2 for example, but as I tried more and more combinations I would get more frustrated! Then I used my foundations and asked myself: “What is a string? Oh a string is an array of chars!” For those who don’t know char or character is a primitive data type along with integer, float, boolean, references
Back to the thought process, if a string is an array of characters and the first position is a dash, I can check that and make some code that works!

This was the change I made:

var formatCurrency = function(element) {
  $this = $(element);
  var value = $this.val();
  var isNegative = (value.charAt(0) === '-') ? true : false

  value = value.replace(/[^0-9,.]/g, '');

  if (isNegative) { value = '-'.concat(value) }

  if ($this.attr('only_integer')) {
    value = integerFieldFormatter(value);
  } else {
    value = decimalFieldFormatter(value);
  }

  $this.val(value);
  $this.next().val(value.replace(/[\,]/g, '.'));
};

2 lines of code without any regex.

Also added values to test:

'-1245,353': '-1245,35' // float
'-1245,353': '-1245' // integer

If for any reason you don’t understand the String methods used, head to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

I hope I helped.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s