Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts

    Convert number to American Dollars, a gift for you.

    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.

    Code:
    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;
                }
            })();

  • #2
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Too bulky code. Make it easy as you can :=) For example

    Code:
    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:
    Code:
    Number.prototype.$ = function()
    {
    	return (this < 0 ? '-$' : '$') + Math.abs(this).toFixed(2);
    };
    
    var n = 12;
    alert(n.$());

  • #3
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts

    Smile

    Quote Originally Posted by siberia-man View Post
    Too bulky code. Make it easy as you can :=) For example

    Code:
    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:
    Code:
    Number.prototype.$ = function()
    {
    	return (this < 0 ? '-$' : '$') + Math.abs(this).toFixed(2);
    };
    
    var n = 12;
    alert(n.$());
    great comments
    why not post a completed function ?

  • #4
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Although we use dollars here but our currency is ruble and we do not need in this function even for rubles :=)

  • #5
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    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.

    Code:
    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.$());

  • Users who have thanked siberia-man for this post:

    DaveyErwin (10-14-2010)

  • #6
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts
    you have posted a very nice code and I am
    so happy to steal it, ThankYou!

  • #7
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Quote Originally Posted by DaveyErwin View Post
    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.

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,142
    Thanks
    203
    Thanked 2,547 Times in 2,525 Posts
    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:-


    Code:
    <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>
    Last edited by Philip M; 10-15-2010 at 10:08 AM.

  • #9
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    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

  • Users who have thanked siberia-man for this post:

    Philip M (10-16-2010)

  • #10
    New Coder
    Join Date
    Sep 2010
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Smile formatting numbers

    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.

  • #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,142
    Thanks
    203
    Thanked 2,547 Times in 2,525 Posts
    Quote Originally Posted by u jayakodi View Post
    I have used it in IE with no hitch.
    It will work ONLY in IE, therefore rather useless.

  • #12
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    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.

    Code:
    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:
    Code:
    /*
    
    @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

  • #13
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,142
    Thanks
    203
    Thanked 2,547 Times in 2,525 Posts
    Sadly it does not work with decimal numbers.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #14
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    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?

  • #15
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,142
    Thanks
    203
    Thanked 2,547 Times in 2,525 Posts
    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

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •