I have looked through countless threads here and elsewhere for over 2 days and I cannot get this to work properly.
I have a calculator working exactly the way I need it to, however, I can't seem to get one last thing complete. Comma separator by thousands with decimal.
I have the decimal places, but can't add commas. When I do add commas, I can get one or two fields to work before the calculation breaks or the value is displayed as NaN.
Here is the working page: http://codepen.io/anon/pen/Fauzy
It currently uses this:
function FormatAsMoney(mnt) {
mnt -= 0;
mnt = (Math.round(mnt*100))/100;
return (mnt == Math.floor(mnt)) ? mnt + '.00'
: ( (mnt*10 == Math.floor(mnt*10)) ?
mnt + '0' : mnt);
}
If I try to use this :
function FormatAsMoney(x)
{
var money_value;
mnt = x.value;
mnt = mnt.replace(/\,/g,'');
mnt -= 0;
mnt = (Math.round(mnt*100))/100;
money_value = (mnt == Math.floor(mnt)) ? mnt + '.00' : ( (mnt*10 == Math.floor(mnt*10)) ? mnt + '0' : mnt);
if (isNaN(money_value))
{
money_value ="0.00";
}else{
money_value = CommaFormatted(money_value);
x.value = money_value.replace(".00", "");
}
}
It doesn't work at all.
I did another test using :
function FormatAsMoney(str) {
return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
});
}
In which I get the comma formatting on the first field, but lose decimals and it does not continue any other calculation.
As another example I created another function to add the commas like :
function addCommas(nStr){
nStr += '';
c = nStr.split(','); // Split the result on commas
nStr = c.join(''); // Make it back to a string without the commas
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;
}
I then use it like:
document.Rate.RATE.value=addCommas(FormatAsMoney(dasum));
Which seems to be the best outcome I have had yet, however on line (163) where, for example, function dosum()
depends on many if statements, It breaks the again. I can't seem to get it to work for all applicaable fields where the value would be in thousands.
I need to be able to enter the "Insured Amount" at the top 20 million dollars "20000000" (as an example because it will populate almost all possible fields that will have a comma separated values with a decimal place)
Can anyone end my misery? Thanks for any help.