...

View Full Version : format euro currency



skynet
01-19-2012, 02:11 PM
We format euro currency as 1.000.000,00 (just the opposite of USD).
Anyone who could give me a script that changes the input into this format?
I tried 'replace' with a regular expression, but my regexes don't work.

devnull69
01-19-2012, 02:50 PM
function addSeparators(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}

// example call: addSeparators(1231231231.45)
// will give 1.231.231.231,45

skynet
01-19-2012, 03:15 PM
Thank you very much for your instantaneous reply.
It works already very good, but could you make it foolproof too?
There has to be a decimal comma followed by two digits.
Input of 1234 should result in 1.234,00
Input of 1234,5 should result in 1.234,50
Input of 1234,123 should result in 1.234,12 or give a warning that there only can be 2 digits after the comma.

Philip M
01-19-2012, 05:28 PM
Try this:-


<script type = "text/javascript">

var num = 1234567890123.45345 //works with negative numbers as well

num = Math.round(num*Math.pow(10,2))/Math.pow(10,2); // to 2 decimal places

document.write('<span id="count"></span>');

document.getElementById('count').innerHTML = addCommas(String(num));

function addCommas(nStr) {
nStr = nStr.replace(/[^0-9\.]/g,"");
var rgx = /(\d+)(\d{3})/;
while (rgx.test(nStr)) {
nStr = nStr.replace(rgx, '$1,$2');
}
nStr = "$" + nStr;
if (nStr.indexOf('.') == -1) { // if whole number add .00
nStr = nStr + ".00";
}
nStr = nStr.replace(/,/g, '#').replace(/\./g, ',').replace(/#/g, '.'); // display continental format
return nStr;
}

</script>

Or for values entered by the user:-


<input type = "text" name = "num" id = "num" onkeyup = "addCommas2(this.value)"><br><br>

<span id="count1"></span><br>

<script type = "text/javascript">

function addCommas2(nStr) {
nStr = nStr.replace(/[^0-9\.]/g,""); // strip non-numeric
document.getElementById('num').value = nStr;
var rgx = /(\d+)(\d{3})/;
while (rgx.test(nStr)) {
nStr = nStr.replace(rgx, '$1,$2');
}
nStr = nStr.replace(/,/g, '#').replace(/\./g, ',').replace(/#/g, '.'); // display continental format
document.getElementById('count1').innerHTML = nStr;
}

</script>

If you are 20 and you are not a socialist, then you have no heart. If you are 40 and you are still a socialist, then you have no brain.

skynet
01-19-2012, 06:08 PM
It works like a dream.
Concerning the foolproof parts:
Input of 1234 should result in 1.234,00: I found this in your first example.
Input of 1234,5 should result in 1.234,50
Input of 1234,123 should result in 1.234,12 or give a warning that there only can be 2 digits after the comma.: I'll try to add this myself.
Many, many thanks !

Philip M
01-19-2012, 06:18 PM
Add this line in blue:-


function addCommas2(nStr) {
nStr = nStr.replace(/[^0-9\.]/g,""); // strip non-numeric
nStr = nStr.replace(/(\.\d)(\d)(\d+)$/,"$1$2"); // truncate input to 2 decimal places only
document.getElementById('num').value = nStr;

and this



nStr = nStr.replace(/(\.\d)$/, "$10"); // show 2 decimal places with final 0 if only one entered
nStr = nStr.replace(/,/g, '#').replace(/\./g, ',').replace(/#/g, '.'); // display continental format
document.getElementById('count1').innerHTML = nStr;

Instead of the $ sign you will want to use &euro;

skynet
01-20-2012, 09:59 AM
Much obliged. Thank you very much for your help.
The last thing that doesn't seem to work is:
nStr.replace(/(\.\d)$/, "$10"); // show 2 decimal places with final 0 if only one entered
Entering 1234.5 results in 1.234,5 instead of 1.234,50

Philip M
01-20-2012, 11:16 AM
Much obliged. Thank you very much for your help.
The last thing that doesn't seem to work is:
nStr.replace(/(\.\d)$/, "$10"); // show 2 decimal places with final 0 if only one entered
Entering 1234.5 results in 1.234,5 instead of 1.234,50

It works for me and I get 1.234,50 :)

You may care to add another line to cover the case where the user enters a decimal point with nothing after it.

nStr = nStr.replace(/\.$/,".00"); // add 00 to decimal point with no digits following
nStr = nStr.replace(/(\.\d)$/, "$10"); // show 2 decimal places with final 0 if only one entered
nStr = nStr.replace(/,/g, '#').replace(/\./g, ',').replace(/#/g, '.'); // display continental format

skynet
01-20-2012, 11:44 AM
I admire your knowledge of regular expressions and do believe it works for you.
I tried this in several browsers but my result stays the same: entering 1234.5 gives 1.234,5 instead of 1.234,50.
I respect your precious time, but could you please post here the complete page you are using, so I can exclude possible errors I made in mine ? At the moment, I can't find any in my page.
You did help me a lot already, and want to thank you for this.

Philip M
01-20-2012, 03:23 PM
<input type = "text" name = "num" id = "num" onkeyup = "addCommas2(this.value)"><br><br>

<span id="count1"></span><br>

<script type = "text/javascript">

function addCommas2(nStr) {
nStr = nStr.replace(/[^0-9\.]/g,""); // strip non-numeric
nStr = nStr.replace(/(\.)(\d+)?(\.)/,"$1$2"); // only one decimal point
nStr = nStr.replace(/(\.\d)(\d)(\d+)$/,"$1$2"); // truncate to 2 decimal digits only
document.getElementById('num').value = nStr; // write entry back to the field
var rgx = /(\d+)(\d{3})/;
while (rgx.test(nStr)) {
nStr = nStr.replace(rgx, '$1,$2');
}

if (nStr.indexOf(".") == -1) {
nStr += ".00"; // add .00 to whole number (if desired)
}

nStr = nStr.replace(/\.$/,".00"); // add 00 to decimal point with no digits following
nStr = nStr.replace(/(\.\d)$/, "$10"); // show 2 decimal places with final 0 if only one entered
nStr = nStr.replace(/,/g, '#').replace(/\./g, ',').replace(/#/g, '.'); // display continental format
document.getElementById('count1').innerHTML = nStr;
}

</script>

skynet
01-20-2012, 04:00 PM
Great, your code works.
I can't see any difference with my code right away, but there has to be some error in mine.
I already did find a solution for this problem with
if (nStr.charAt(nStr.length-2) == '.') {nStr = nStr+'0';}
That works too, but it's not so nice coded as yours.
Thanks again, I appreciate your help very very much ! You did help me a lot, and saved me from a severe headache.

Philip M
01-20-2012, 05:14 PM
Glad you have got it to work! :) Even a space in the wrong place can prevent a regular expression from working.

skynet
01-21-2012, 11:12 AM
A final question.
An input of our correct format (f.e.: 1.234,56) gives 1,23 as result.
How could I prevent this ?

Philip M
01-21-2012, 12:27 PM
Oh dear! You are not supposed to place anything but digits and a decimal point (.) in the input field. You may not enter a decimal point as a separator, as in European style. The dot . means a decimal point. (12.34)

You are entering 1.23 (one point two three) and so your requirement that only 2 decimal digits are allowed does not allow you to enter any more digits. You cannot enter 1.2345 or of course 1,23 as the comma is ignored.

If you want the user to enter a number with separators (1,234,567) then the whole thing is pointless. The purpose of the script is to format the number by adding the commas (separators) to the plain number 1234567.89, and in your case change the . to a , and the , to a . in the final output. That is what this line does:-


nStr = nStr.replace(/,/g, '#').replace(/\./g, ',').replace(/#/g, '.'); // display continental format

If you wish to allow input of the decimal radix point as a comma (,) then you will need to rewrite the script accordingly, replacing evey literal . (\.) with a literal , (\,) So:


<input type = "text" name = "num" id = "num" onkeyup = "addCommas2(this.value)"><br><br>

<span id="result"></span><br>

<script type = "text/javascript">

function addCommas2(nStr) {
nStr = nStr.replace(/[^0-9\,]/g,""); // strip non-numeric (decimal is ,)
nStr = nStr.replace(/(\,)(\d+)?(\,)/,"$1$2"); // only one decimal comma
nStr = nStr.replace(/(\,\d)(\d)(\d+)$/,"$1$2"); // truncate to 2 decimal digits only
document.getElementById('num').value = nStr; // write entry back to the field
var rgx = /(\d+)(\d{3})/;
while (rgx.test(nStr)) {
nStr = nStr.replace(rgx, '$1.$2');
}

// display continental format

if (nStr.indexOf(",") == -1) {
nStr += ",00"; // add .00 to whole number (if desired)
}

nStr = nStr.replace(/\,$/,",00"); // add 00 to decimal point with no digits following
nStr = nStr.replace(/^\,00/,""); // if entry backspaced out
nStr = nStr.replace(/^\,/,"0,"); // add leading zero if nothing before decimal radix
nStr = nStr.replace(/(\,\d)$/, "$10"); // show 2 decimal places with final 0 if only one entered

document.getElementById('result').innerHTML = nStr;
}

</script>

skynet
01-21-2012, 04:43 PM
The script doesn't need to be rewritten, I'll try to explain it.

The only correct format for us is 1.234,56
On a keypad there isn't a decimal comma, but a decimal point; therefore some people give 1234.56 as input.
Your script corrects this to the right format: 1.234,56
It corrects also the ones who forget the 2 digits after the decimal comma.

The last problem is that if someone already gives the correct input (1.234,56) the script changes this into an unwanted value.

I'm trying to avoid this by inserting as first rule in the script:
IF
(nStr.charAt(nStr.length-3) == ',') // decimal comma at the right place
AND
(nStr.charAt(nStr.length-2).match(/[^0-9]/)) // followed by a digit
AND
nStr.charAt (nStr.length-1).match(/[^0-9]/)) // followed by another digit
THEN
the input is OK and the remaining of the script shouldn't be executed.

Of course, I have not the appropriate skills to make this work.
Would you please be so kind to help me again ?
I am a bit ashamed, and want to thank you already for your patience with me.

Philip M
01-21-2012, 04:51 PM
The last problem is that if someone already gives the correct input (1.234,56) the script changes this into an unwanted value.


I am sorry, I do not understand. It is not possible for the user to enter a dot (period) into the amount entered. In my revised script in post #14 only digits and commas are allowed. If he enters 1234.56 then the script formats that to 1.234,56 - Is that not what you want?

If the problem is to do with your keyboard keypad, then the only remedy is to re-map the keyboard keys and reconfigure the keypad . to , I can't help you with that. Google for e.g. http://www.notebookforums.com/t/58517/how-to-change-your-keyboard-keys or http://www.remapkey.com/

But the dot key on the numeric pad cannot be used in my script. All dots are suppressed. The user must use the comma key on the main keyboard.

There was a typo in the revised code I gave you in post#14 which I have now corrected :o
should be
nStr = nStr.replace(rgx, '$1.$2');

Another improvement is


nStr = nStr.replace(/\,$/,",00"); // add 00 to decimal point with no digits following
nStr = nStr.replace(/^\,00/,""); // if entry backspaced out
nStr = nStr.replace(/^\,/,"0,"); // add leading zero if nothing before decimal radix
nStr = nStr.replace(/(\,\d)$/, "$10"); // show 2 decimal places with final 0 if only one entered

Summary - use the revised and improved code I posted at post #14, but the user must enter a comma for the decimal radix. Dots (periods) may not be entered at all.

skynet
01-22-2012, 10:46 AM
Many thanks for the improvements.
The script is nearly perfect foolproof now.
The very last thing I'm searching for is:
if someone enters the amount in the correct format: don't execute the script !.
Testing the correct format could be done by controlling the last three characters: if there is a comma followed by two digits, then the input is OK and the script can be skipped.
If you could help me with this condition, you would make my day perfect.

Philip M
01-22-2012, 11:01 AM
Many thanks for the improvements.
The script is nearly perfect foolproof now.
The very last thing I'm searching for is:
if someone enters the amount in the correct format: don't execute the script !.
Testing the correct format could be done by controlling the last three characters: if there is a comma followed by two digits, then the input is OK and the script can be skipped.
If you could help me with this condition, you would make my day perfect.

I am sorry, but I am lost again. I don't understand what you mean by "not execute the script". The script works onkeyup - as the data is being entered. And the script must run to determine whether or not the entry ends with a comma followed by two digits.

The script formats a number with separators - why do you not want that to happen if the number ends with two decimal digits? :confused:
And why does it matter if the script changes an entry which is already in the correct format into the same correct format? :confused:

In any case there are always two decimal digits - added automatically.

if (nStr.indexOf(",") == -1) {
nStr += ",00"; // add .00 to whole number (if desired)
}

I am beginning to feel that this topic is unending - and becoming pointless. :(

If you want to make further alterations then please make concrete proposals (and test the code out yourself).

skynet
01-22-2012, 02:37 PM
I agree. What I mean is:
- first check the format: if the format is OK (xxxxxx,dd) don't run the script
- else: run the script

Maybe there is a misunderstanding because I changed 'onkeyup' in 'onblur' (so the script runs after leaving the input field) or because my English is so poor.
Nevertheless, I want to thank you very much for the time you already spent on my problem and do apologize for any inconvenience caused by my inaccurate questions.

Philip M
01-22-2012, 04:30 PM
I agree. What I mean is:
- first check the format: if the format is OK (xxxxxx,dd) don't run the script
- else: run the script

Maybe there is a misunderstanding because I changed 'onkeyup' in 'onblur' (so the script runs after leaving the input field) or because my English is so poor.
Nevertheless, I want to thank you very much for the time you already spent on my problem and do apologize for any inconvenience caused by my inaccurate questions.

Your English is not at all poor - it is very good indeed, and (to my shame) is better than quite a few native speakers who post in this forum.

But if you have changed "onkeyup" to "onblur" then all bets are off. That is not how the script is supposed to run. You would not modify a doctor's prescription, would you? I still don't understand why the script should not be run if the format of the value entered is xxxxxxx,xx.

skynet
01-22-2012, 06:22 PM
Thanks for all your work, I appreciate it very very much.

I think the reason why we don't always understand each other is that I'm focused at our format with dots as separators and a comma as decimal character, you do it the other way.
I use your script in a form - to correct wrong formatted input - the script does the job at the moment the visitor leaves the field.
Only if the visitor is not so lazy as the majority of the people and fills in a correct formatted amount like € 1,12, the script changes this input in 112,00.
(REM: You should replace the comma with a dot.)
To avoid this, I'm trying not to use the script in such cases. Therefore, I inserted as first line in the script
if (nStr.charAt(nStr.length-3) == ',') return;
This means that if the visitor did enter a comma (REM: dot for you) followed by two digits, the input is correct (because in euro, both entries like 1234,56 and 1.234,56 are accepted). If this is not the case, then your script should be executed.

What an explanation !
In less words: this just means that your script does a wonderful job now.
Making a script as foolproof as possible is always a huge challenge.
I keep testing it and found no errors so far.
You did an excellent job and I don't know what words I should use to thank you for helping me out (my English vocabulary is too limited to find the right words): thanks, thanks and thanks again.

Philip M
01-22-2012, 06:31 PM
You did an excellent job and I don't know what words I should use to thank you for helping me out (my English vocabulary is too limited to find the right words): thanks, thanks and thanks again.

Geweldig? Allermachtig prachtig? Of zoiets? Ik onderstel dat u een Belge bent.

skynet
01-22-2012, 11:55 PM
Alhoewel we niet zo ver van elkaar wonen, is onze levenswijze toch totaal anders. Wij rijden rechts, draaien een slot naar rechts om te sluiten, zelfs de richting van de schroefdraad is tegengesteld aan die van jullie. We gebruiken al sinds mensenheugenis het metriek stelsel met meter, liter en kilogram, en ja, we plaatsen een punt waar jullie een komma plaatsen en omgekeerd. We gebruiken zelfs een ander toetsenbord, wij azerty, jullie qwerty. Het is daardoor niet eenvoudig om onze gewoontes opzij te zetten om een probleem op dezelfde manier te benaderen. Enorm veel respect, inderdaad, voor jouw kennnis en erg bedankt voor de geboden hulp. Groeten uit Vlaanderen en misschien tot nog eens. Bedankt, Philip.

Philip M
01-23-2012, 09:20 AM
zelfs de richting van de schroefdraad is tegengesteld aan die van jullie.

:confused: Dat geloof ik niet! U houdt me voor de gek! En toch jullie gebruiken ook "pond" (.5 kilo), nietwaar?

skynet
01-23-2012, 06:18 PM
Dit was louter ter illustratie van onze verschillende perceptie: wij draaien steeds een bout in 'met de klok mee'. 'Linkse' bouten en moeren kwamen vroeger vrij frequent voor in combinatie met niet-metrische schroefdraad, in dit geval gebruiken wij daarvoor nog steeds de benaming 'Engelse draad' (bijvoorbeeld bij het linker pedaal van een fiets).
Pond (500 gr) en ons (100 gr) worden in Nederland nog in de spreektaal gebruikt, alhoewel die eenheden ook daar in 1937 wettelijk afgeschaft werden: een winkelier mag deze benamingen bijvoorbeeld niet op zijn prijskaartje gebruiken. In BelgiŽ leunen we daarvoor dicht aan bij Frankrijk waar 'pond' en 'ons' wettelijk afgeschaft werden in 1799. Deze eenheden zijn bij ons ongebruikelijk geworden, ook in de spreektaal.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum