tags:

views:

87

answers:

1

Hi ,

How do i convert a danish number to an english format for example : 8,5 is decimal number representation in danish and in english it would be 8.5 Now i need to convert 8,5 to 8.5 my current culture is danish and i am trying to convert this in javascript (NOT C#)

Regards, Francis P.

+2  A: 

If it's in a string, you can just use:

newstr = oldstr.replace(/,/,".");

For example, head on over to W3Schools and enter:

<html><body>
    <script type="text/javascript">
        var oldstr="8,5";
        var newstr = oldstr.replace(/,/,".");
        document.write(newstr);
    </script>
</body></html>

to get:

8.5

If you want to swap the thousands separators and decimal point, it's a little bit trickier:

<html><body>
    <script type="text/javascript">
        var oldstr="1.472.318,5";
        var newstr = oldstr.replace(/,/,"xyzzy");
        newstr = newstr.replace(/\./g,",");
        newstr = newstr.replace(/xyzzy/,".");
        document.write(newstr);
    </script>
</body></html>

will give you:

1,472,318.5

If you want to intelligently figure out which separator is being used, that's even trickier. What I would do in that case is analyse the string for specific formats. Check how many of each of the . and , characters are and ensure the one with a count of one is treated as the decimal. But that will not work for edge cases like 1,500 - is that fifteen hundred or one point five?

What I would do then is simply put a big message on the web page along the lines of:

Please ensure all amounts are entered in U.S. format (with comma for thousands separator and period for decimal point).

Sometimes you just have to tell the client what's right :-)

paxdiablo
To do more than one (think thousands separator, which has this same problem), you need the global flag on that.
T.J. Crowder
Thanks pax, But my application could culture cn be changed .that is i can select a culture of danish ,English
francisf
Well, just store the numbers in the English format (easier to deal with) and use the "English-to-Danish" conversion provided by @paxdiablo only if the user selected Danish.
nico