I use the code to add zero after my values and take help from internet and found this code
$(document).ready(function() {
//var number = 258.20;
var number = 2;
var rounded = number.toFixed(2); // rounded = 258.20
document.write(rounded);
});
and added to my project but later I figure out that this code is not working with cents, I checked this code with my test cases and found that it is not working properly. If I use value 0.99
its convert into 0.00
and when I use value 45
its working fine 45.00
but when I use extra cost is 0.99 cents
its convert into NaN
. I try to find every where but didn't get succeeds. So is there any way to find the numbers in value and check it, if it is number it should add zeros, if its cents it should work with cents value and if the value is with string it should work also with it.
I found the solution and here it is.
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
//var testCases = "extra cost is 0.99 cents";
//var testCases = 255;
//var testCases = 0.36;
//var testCases = 25;
//var testCases = 1;
//var testCases = 1000;
//var testCases = 10000;
//var testCases = 100000;
//var testCases = 0.53789;
var testCases = 0.43789;
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
if(isAlphaNumeric(testCases)) {
document.write((testCases).formatMoney(2, '.', ','));
} else {
document.write(testCases);
}