I have what I thought was a simple problem but am finding it hard to find easy solutions. I have a donation page and people can enter their amount. The problem is that some cultures use a period to indicated the decimal and others use a comma. I am also rounding to the nearest whole number.

Is there an easy way to format the number such that:

12.95 will equal 13. 12,95 will equal 13. 12,000 will equal 12000. 12 000 will equal 12000. 12.000 will equal 12000. 12.45 will equal 12. 12,45 will equal 12.

Basically I need to strip out any commas and periods and create an appropriate whole number. This needs to be based on the number actually entered, as some people may be using a European computer and keyboard but wishing to donate a US dollar amount, etc.

Thank you!

有帮助吗?

解决方案

Here is the shortest solution that will work an all given examples. I check for the third to last character, and if its comma or dot I assume it as an integer separator.

function parse(source) {
    var sep = source.charAt(source.length - 3);

    switch (sep) {
        case '.':
        case ',':
            var parts = source.split(sep);
            var norm = parts[0].replace(/(\.|,|\s)/g, '') + '.' + parts[1];
            break;
        default:
            var norm = source.replace(/(\.|,|\s)/g, '');
    }

    return Math.round(Number(norm));
}

Demo: http://jsfiddle.net/5C4aN/2/

Also have a look on accounting.js which does good job formatting/parsing currencies.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top