...

View Full Version : How Can I Multiplying Currency?



Glass Casket
09-04-2007, 07: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

Glass Casket
09-05-2007, 03:10 AM
Any ideas?

chump2877
09-05-2007, 05: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">
function addCommas(nStr)
{
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;
var productString = addCommas(newNum.toFixed(2));
alert(productString);
</script>

chump2877
09-05-2007, 06: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!";
var productString = addCommas(newNum.toFixed(2));
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!";
}

function addCommas(nStr)
{
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
alert(doCurrencyMath("25,000.00",null,2,operators[2]));

// print 25,000,000.50 - 5
alert(doCurrencyMath("25,000,000.50",null,5,operators[1]));

// print 0.50 + 15.50
alert(doCurrencyMath("0.50",null,15.50,operators[0]));

//print 25,000.00 / 12,500.00
alert(doCurrencyMath("25,000.00","12,500.00",null,operators[3]));

//produce errors
alert(doCurrencyMath("25,000.00","25,000.00",5,operators[0]));
alert(doCurrencyMath("25,000.00","25,000.00",null,"="));


</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum