1

i have user input containing a number with decimals. i have to modify that input to a format which i can use to do calculations on.

So, consider the following:

input         -->    should become
10,123.15     -->    10.123,15
10.123,15     -->    10.123,15
10,123.1      -->    10.123,10
10.123,1      -->    10.123,10
10,123        -->    10,123,00
10.123        -->    10.123,00
10.123,13562  -->    10.123,14
10,123.13562  -->    10.123,14

In other words: use dots for thousand separators, comma for decimal separator en always return a rounded up, two decimal number.

I tried using regex'es, substr, round, but i'm kinda stuck. I have it working now for the first two examples mentioned above but now it doesn't work for the rest.

Been looking it at this for a few hours now but maybe you can help me with it? JQuery Number Formatting did help me a bit but still it's not working for all of the examples above.

I would be so happy if someone could help me with this!

1
  • 1
    If comma before dot, 1. remove commas, 2. use toFixed(2), 3. reformat using one of many european number formatters - If dot before comma replace dots with nothing, replace commas with dots. rinse and repeat Commented Aug 21, 2016 at 13:04

2 Answers 2

1

You can use toLocaleString() to achieve this if you provide a locale which formats number in the manner you require; de-DE for example. Try this:

var foo = '10,123.15'; // number as string
var num = parseFloat(foo.replace(',', '')); // remove the , and convert to float
console.log(num.toLocaleString('de-DE')); // format to locale

Sign up to request clarification or add additional context in comments.

Comments

-1

Iterate the input val from right to left while testing if the char is a comma or dot and then act accordingly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.