PDA

View Full Version : How Can I Multiplying Currency?

09-04-2007, 06:24 PM
For example, if I have 25,000.00 * 2, how could I get 50,000.00 in return? Also, what if I have cents as my price?

Thanks

09-05-2007, 02:10 AM
Any ideas?

chump2877
09-05-2007, 04:52 AM
it sounds like you are concerned about the manipulation and formatting of currency strings, but your question isn;t posed very well...

In any event, you want something like this perhaps:

<script type="text/javascript">
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '\$1' + ',' + '\$2');
}
return x1 + x2;
}
var amountString = "25,000.00";
amountString = amountString.replace(/,/g,"");
var num = parseInt(amountString);
var newNum = num * 2;
</script>

chump2877
09-05-2007, 05:41 AM
a more flexible version, for doing different types of currency arithmetic:

<script type="text/javascript">

var operators = new Array("+","-","*","/");

function doCurrencyMath(currencyString,currencyString2,num,operator)
{
var currencyNum = parseFloat(currencyString.replace(/,/g,""));
var newNum;
if (num == null && currencyString2 != null)
{
var currencyNum2 = parseFloat(currencyString2.replace(/,/g,""));
newNum = getNewNum(operator,currencyNum,currencyNum2)
}
else if (currencyString2 == null && num != null)
{
newNum = getNewNum(operator,currencyNum,num)
}
else
{
return "Error!";
}
if (newNum == "Error!")
return "Error!";
return productString;
}

function getNewNum(operator,num1,num2)
{
if (operator == "+")
return num1 + num2;
else if (operator == "-")
return num1 - num2;
else if (operator == "*")
return num1 * num2;
else if (operator == "/")
return num1 / num2;
else
return "Error!";
}

{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = (x.length > 1) ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '\$1' + ',' + '\$2');
}
return x1 + x2;
}

// Test currency arithmetic
// Either the second or third parameter of doCurrencyMath() must be null, or an error will be returned.
// For doCurrencyMath(), the first and second parameters are strings, the third is a number, and the fourth is the operator array member.

// print 25,000.00 * 2

// print 25,000,000.50 - 5