View Full Version : Convert number to American Dollars, a gift for you.
DaveyErwin
10-14-2010, 02:27 PM
Here is a script for converting
a number to american dollars
(i wish i could convert this script to dollars).
Please comment and help make this script better.
numToDollars =
(function () {
var a = function (m) {
var t, s = Math.round(m * Math.pow(10, 2)) + "", start, end;
if (/\D/.test(s)) { return "" + m; }
s = s + "";
while (s.length < 3) { s = '0' + s; }
start = s.substring(0, t = (s.length - 2));
end = s.substring(t);
if (end) { end = "." + end; }
var a = 3;
while (start.charAt(a)) {
start = start.substr(0, start.length - a) + "," + start.substr(start.length - a);
a += 4;
}
return start + end;
}
return function (n) {
var u = a(Math.abs(n));
return (n < 0 ? "-$" : "$") + u;
}
})();
siberia-man
10-14-2010, 02:44 PM
Too bulky code. Make it easy as you can :=) For example
function numToDollars(n)
{
return (n < 0 ? '-$' : '$') + Math.abs(n).toFixed(2);
};
var n = 12;
alert(numToDollars(n));
The next example is JavaScript way -- prototype based implementation:
Number.prototype.$ = function()
{
return (this < 0 ? '-$' : '$') + Math.abs(this).toFixed(2);
};
var n = 12;
alert(n.$());
DaveyErwin
10-14-2010, 02:46 PM
Too bulky code. Make it easy as you can :=) For example
function numToDollars(n)
{
return (n < 0 ? '-$' : '$') + Math.abs(n).toFixed(2);
};
var n = 12;
alert(numToDollars(n));
The next example is JavaScript way -- prototype based implementation:
Number.prototype.$ = function()
{
return (this < 0 ? '-$' : '$') + Math.abs(this).toFixed(2);
};
var n = 12;
alert(n.$());
great comments:)
why not post a completed function ?
siberia-man
10-14-2010, 02:50 PM
Although we use dollars here but our currency is ruble and we do not need in this function even for rubles :=)
siberia-man
10-14-2010, 03:53 PM
Here I use regular expressions to separate thousands by comma.
From the Friedl's book "Mastering Regular Expressions" I remember that a separating of thousands by comma does not have trivial solution. Also I remember that regular expressions in JavaScript don't support many PCRE features so I am using a loop to look up all thousands.
Number.prototype.$ = function()
{
var n = Math.abs(this).toFixed(2);
while ( arguments.callee.re.test(n) ) {
n = n.replace(arguments.callee.re, '$1,');
}
return (this < 0 ? '-$' : '$') + n;
};
Number.prototype.$.re = /(\d)(?=\d\d\d(?:,|\.))/;
var n = 12;
alert(n.$());
DaveyErwin
10-14-2010, 05:04 PM
you have posted a very nice code and I am
so happy to steal it, ThankYou!
siberia-man
10-14-2010, 08:36 PM
you have posted a very nice code and I am
so happy to steal it, ThankYou!
You're welcome. I'll be glad if my experience will help to somebody else.
Philip M
10-15-2010, 09:28 AM
See:- http://www.codingforums.com/showthread.php?t=17515.
This topic is old news and has been covered several times recently in the proper forum.
Most recently at http://www.codingforums.com/showthread.php?t=206982
Here is another way:-
<script type="text/javascript">
// works with negative numbers also
function formatNumber(x){
return x.toFixed(2).toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
}
var num = formatNumber(1234567.8976);
num = "$" + num;
alert (num);
</script>
siberia-man
10-16-2010, 12:34 PM
Hi Philip M,
Thank you for pointing to the forum rules - in any case, it is very useful for everybody and forces to refresh rules in our minds.
Your implementation is well too -- simple and compact code. BUt I have one notice -- 'toFixed' method returns string so no need to use 'toString' method
u jayakodi
10-30-2010, 12:14 PM
u jayakodi
jayakodiu@yahoo.com
VBS function formatnumber(x) does it neat; just add $. The following javascript code invokes the VBS:
<script language=javascript>
var ele=document.createElement("script")
var nn=document.body.appendChild(ele)
nn.setAttribute("language","vbs")
nn.text="sub fmt(x)"+"\n"+"fx=formatnumber(x)"+"\n"+"end sub"
var fx
fmt(123456789.4589)
alert('$'+fx)
</script>
Alternatively, just add the VBS function in the head tag. I have used it in IE with no hitch.
Philip M
10-30-2010, 08:39 PM
I have used it in IE with no hitch.
It will work ONLY in IE, therefore rather useless. :(
siberia-man
07-31-2011, 12:39 AM
Continuing this thread.
Originally, this is not mine. Looking fresh threads on one forum I found this example. The following code is shorter and smarter and can help to achive a requested thing.
var str = 'Lorem ipsum 234456234 Lorem ipsum 7345287346 asdfae';
alert(str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 '));
I have modified it to this looks like an universal function:
/*
@param str String input string where all numbers will be formatted
@param sep String separator that will divide each 3 digits (default value is a whitespace)
*/
function formatNumber(str, sep)
{
return str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1' + (sep || ' '));
};
var str = 'Lorem ipsum 234456234 Lorem ipsum 7345287346 asdfae';
var formatNumber(str); // Lorem ipsum 234 456 234 Lorem ipsum 7 345 287 346 asdfae
var formatNumber(str, ','); // Lorem ipsum 234,456,234 Lorem ipsum 7,345,287,346 asdfae
Philip M
07-31-2011, 11:16 AM
Sadly it does not work with decimal numbers. :(
siberia-man
07-31-2011, 01:43 PM
Philip M
Hmm... What do you mean saying "does not work"?
Of course, before publishing this I have tested on integer and fixed-point numbers. In both cases it separates thousands properly. I saw that it separates thousandth parts after the floating point too. Do you mean that thousandth should not be highlighted? Is there rule -- how to show thousandth?
Philip M
07-31-2011, 03:51 PM
Yes, I should have said that it does not work with decimal numbers where there are 4+ places of decimals.
var str = 'Lorem ipsum 234456234.1234 Lorem ipsum 7345287346.1234 asdfae';
Results in:- 234,456,234.1,234 Lorem ipsum 7,345,287,346.1,234 asdfae
Dreamshaper
08-18-2011, 02:58 AM
Pretty cool, but I agree the code is too bulky and there is some breaks in the code which could make it crash I reakon so anyway but still a top effort!
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.