PDA

View Full Version : Help needed with replace function in Javascript

denhamd2
10-13-2009, 01:03 PM
Hi,

I'm having a problem with a replace function in my Javascript code. Basically I am taking a number "housevalue" and dividing it and rounding it up. Because the value was sometimes coming in in the format "3,45 houses" I needed to convert it to "3.45 houses" in order to get a proper decimalised number so I could divide it. However, the final outputted number I get always comes out like 0.93 (it always has a "." in it). Is there any way possible of outputting the number in the same format as it came in as - ie having a comma or having a dot (not always having a dot)? Here is my function below, and help would be greatly appreciated!

<script type="text/javascript">
function roundVal(val)
{
var dec = 2;
return Math.ceil(val * Math.pow(10, dec)) / Math.pow(10, dec);
}

function doit(val)
{
var matches = /([^0-9.,]*)([0-9.,]+)([^0-9.,]*)/.exec(val);
matches[2] = roundVal((parseFloat(matches[2].replace(/,/g, '.')) / 12) / 3);
return matches[1] + matches[2] + matches[3];
}
</script>

<script type="text/javascript">
var housevalue = '&euro;19,3534211 EUR';
document.write(doit(housevalue));
</script>

jscheuer1
10-13-2009, 05:16 PM
I think this would be easier to to work out if I knew what the exact desired result from your above code should be.

Also helpful would be the normal math involved, forget about converting numbers with commas to numbers with decimals or even using javascript, just tell us what you want to do, ex:

19,3534211 divided by what? rounded to how many places? etc.

Another thing I'm curious about, here in the states, the commas in numbers (though being phased out) denote thousands, millions, billions, etc. in groupings of three non-decimal places (to the left of the decimal point). However, in many if not all European countries I believe it means the same thing as a decimal point does here. Is that the sense in which you want the comma interpreted?

jscheuer1
10-13-2009, 05:44 PM
I've looked at this a bit more, and here:

var dec = 2;
return Math.ceil(val * Math.pow(10, dec)) / Math.pow(10, dec);

is just a long way to get:

return Math.ceil(val * 100) / 100;

and this part:

matches[2] = roundVal((parseFloat(matches[2].replace(/,/g, '.')) / 12) / 3);

takes 19,3534211 and first changes it to (parseFloat(matches[2].replace(/,/g, '.'))):

19.3534211

Then it divides it by 12:

1.6127850916666666666666666666667

Then divides it by 3:

0.53759503055555555555555555555556

Then rounds it up to 2 decimal places:

0.54

So if you want a different number as the result, you must perform different math upon the number. By the way, the g global switch in the regular expression is useless. If the input number has more than one comma, it will output as a number with more than one decimal point (NaN) which will break the rest of the math in the code.