1

I have a value that is formatted like 2.083.817. When using jquery script CounterUp it gives me a NaN - probably because of the two "." separators.

The value is being converted with this:

var nums = [];
var divisions = $settings.time / $settings.delay;
var num = $this.text();
var isComma = /[0-9]+,[0-9]+/.test(num);
num = num.replace(/,/g, '');
var isInt = /^[0-9]+$/.test(num);
var isFloat = /^[0-9]+\.[0-9]+$/.test(num);
var decimalPlaces = isFloat ? (num.split('.')[1] || []).length : 0;

I am not quite sure how I can get the script to handle the value with the two "." separators.

Morten Hagh
  • 2,055
  • 8
  • 34
  • 66

2 Answers2

1

The solution is for the most of the time so close, that you will have a hard time finding it..

for (var i = divisions; i >= 1; i--) {

      // Preserve as int if input was int
     var newNum = parseInt(num / divisions * i);

      // Preserve float if input was float
        if (isFloat) {
            newNum = parseFloat(num / divisions * i).toFixed(decimalPlaces).replace(".", ",");
       }

                    // Preserve commas if input had commas
                    if (isComma) {
                        while (/(\d+)(\d{3})/.test(newNum.toString())) {
                            newNum = newNum.toString().replace(/(\d+)(\d{3})/, '$1' + '.' + '$2');
                        }
                    }

                    nums.unshift(newNum);
                }

I just reverse it so it will be 2,083,817 in the html and then replace "," with a "." to get the desired output. Probably not the most perfect solution, but it works.

Morten Hagh
  • 2,055
  • 8
  • 34
  • 66
0

Although I think there's an easier way, you can go with

Number("2.083.817".replace(new RegExp("\\.", 'g'), ""))

Or generically

Number(number_variable.replace(new RegExp("\\.", 'g'), ""))

If you're going to apply this replacement inside a loop, I suggest you store the regex into a variable previously. Like:

regex_replacement = new RegExp("\\.", 'g')

for ....... {
    actual_number = Number(number_variable.replace(regex_replacement, ""))
}

PS: As adapted from javascript replaceAll question

Community
  • 1
  • 1
Gabriel L. Oliveira
  • 3,922
  • 6
  • 31
  • 40