Format currency field with JavaScript

Last month I got a solution to format the currency fields from Wundertax’s declarations

This is the function:

var formatCurrency = function(element) {
  $this = $(element);
  var number = $this.val()
  number = number.replace(/[^0-9,.]/g, '')
  if (number === '') {
    number = '0,00'
  } else {
    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)
      number = number.replace('.', ',')
    } else {
      number = number.replace(',', '.')
      number = parseFloat(number).toFixed(2)
      number = number.replace('.', ',')
    }
  }

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

The following gems were added to the Gemfile:

gem 'jasmine'
gem 'rails-assets-jasmine-fixture', source: 'https://rails-assets.org'
gem 'rails-assets-jasmine-jquery', source: 'https://rails-assets.org'

The last 2 gems gives some useful helpers.

The following lines were edited in the jasmine.yml

spec_files:
  - '**/*[sS]pec.{js.jsx, jsx}'
  - '*[sS]pec.js'

And the tests:

//= require jasmine-fixture
//= require jasmine-jquery

describe('Formats the currency field', function() {
  var $currency_field;
  var values = {
    'aaaa': '0,00',
    '123.456.7890': '123456,79',
    '123,456,7890': '123456,79',
    '123.456.789': '123456,79',
    '123,456,789': '123456,79',
    '123.456,78': '123456,78',
    '123,456.78': '123456,78',
    '123,4': '123,40',
    '123,45': '123,45',
    '12,34567': '12,35',
    '123,4567': '123,46',
    '123,456': '123,46',
    '123 456': '123456,00',
    '123.456': '123,46',
    '123.45': '123,45',
    '123.4': '123,40',
    '123': '123,00'
  }

  beforeEach(function(){
    $currency_field = affix('.js-currency-field input[type=text]');
  });

  function test_all_inputs(input, output) {
    it('formats the number ' + input + ' into ' + output, function() {
      $currency_field.val(input);
      formatCurrency($currency_field);
      expect($currency_field.val()).toEqual(output);
    });
  }

  for (var input in values) {
    test_all_inputs(input, values[input]);
  }
});

Run it:

bundle exec rake jasmine

…and check localhost:8888

See you next week.

Advertisements

One thought on “Format currency field with JavaScript

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