user284503
user284503

Reputation: 378

Only use right most decimal point for Number Value, remove the rest

When a User accidentally enters two more more decimal points, I want to only use the Right Most decimal point.

So: 1234..55 would equal 1234.55

It's easy to make typos, but I have not seen any good code to handle this in Javascript

Upvotes: 0

Views: 225

Answers (2)

metalfight - user868766
metalfight - user868766

Reputation: 2750

You can simply replace multiple occurrence of . (dot) with single . (dot)

By this way it will be able to handle more cases.

var str='1234...55';
var n=str.replace(/(\.)+/,".");
alert(n);

Demo : http://jsfiddle.net/DxKx7/

Upvotes: 0

Guffa
Guffa

Reputation: 700840

Find the last period, split the string there, remove the periods from the first string, and put them together again:

var index = input.lastIndexOf('.');
if (index != -1) {
    input = input.substr(0, index).replace(/\./g, '') + input.substr(index);
}

Demo: http://jsfiddle.net/Guffa/3jBb5/

Upvotes: 3

Related Questions