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.
Results 1 to 12 of 12
  1. #1
    New Coder
    Join Date
    Jul 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Formatting Numbers in Javascript

    I am creating a calculator app and I'm a bit stuck with number formatting.

    Example of how I would like a number to be formatted:
    $2,899,799

    I currently have the formatting working except for the commas. I'm using the following code to achieve this.
    My result is currently showing up like this $2899799

    Code:
    function format (expr, decplaces) {
        var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces))
        while (str.length <= decplaces) {
            str = "0" + str
        }
        var decpoint = str.length - decplaces
        return str.substring(0,decpoint) + str.substring(decpoint,str.length);
    	}	
    
    function dollarize (expr) {
    	return "$" + format(expr,0)
    
    //RESULT FIELDS
    form.AnnualScrapSales.value = dollarize(((A - B) * (C2/100)) * G2)
    is there a way to add to this "function format" code to also achieve the commas?

  • #2
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Find answers for your questions here http://www.codingforums.com/showpost...98&postcount=5. Go back for more details if you need them. (-:

  • #3
    New Coder
    Join Date
    Jul 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts
    RE: Siberia-man

    I'm afraid that I'm not really sure how I would integrate that code into my already existing code. I attempted to simply add it to my function format code like this:

    Code:
    function format (expr, decplaces) {
        var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces))
        while (str.length <= decplaces) {
            str = "0" + str
        }
        var decpoint = str.length - decplaces
        return str.substring(0,decpoint) + str.substring(decpoint,str.length);
    	}	
    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.$());
    It didn't do anything when I tested.

  • #4
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Hi tbrand,

    Let's clarify your request to be sure that we are considering one thing.

    You need format number with the following rules:

    you have some numeric values -- for example, 123456789

    1. you need insert commas to separate thousands with as here 123,456,789
    2. you need add the dollar sign '$' as here $123,456,789

    To achieve these just use the function that was suggested you

    Code:
    var n = 123456789;
    var f = n.$(); // will result to the string '$123,456,789'
    In your case -- do like this:
    Code:
    form.AnnualScrapSales.value = (((A - B) * (C2/100)) * G2).$();
    Last edited by siberia-man; 07-18-2011 at 08:44 PM. Reason: continue to edit

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

    tbrand (07-18-2011)

  • #5
    New Coder
    Join Date
    Jul 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Okay I will play around with this a bit. Thank you.
    Last edited by tbrand; 07-18-2011 at 09:35 PM.

  • #6
    New Coder
    Join Date
    Jul 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts
    RE: Siberia-Man

    Thank you for the suggestion - I did get it to work. Your second post was the clarification I needed. Thank you.

    Only one issue with this - using this code I'm getting the two decimal places in my result field....I don't want any decimal places at all. Not even .00

    I tried to change this as follows (see red) but after doing so the function doesn't work at all. Ideas?

    Code:
    Number.prototype.$ = function()
    {
    	var n = Math.abs(this).toFixed(0);
    
    	while ( arguments.callee.re.test(n) ) {
    		n = n.replace(arguments.callee.re, '$1,');
    	}
    
    	return (this < 0 ? '-$' : '$') + n;
    };
    
    Number.prototype.$.re = /(\d)(?=\d\d\d(?:,|\.))/;

  • #7
    New Coder
    Join Date
    Jul 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts
    One more question.

    In addition to getting rid of the decimal places ( I still haven't figured that one out yet) I'm also having trouble getting this code to work with the following result field:

    Code:
    form.RunQuantity.value = G
    It works fine with all the other results, but can't seem to get it to do it with this one.

    I've tried:
    G.$();
    (G).$();
    (G.$());

    no luck. I just get a blank field.

  • #8
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Hi tbrand,

    Nice to hear that this suggestion works for you. Answering for your first question I can recommend to apply the following modification (see marked substrings).

    Code:
    Number.prototype.$ = function(f)
    {
    	var n = Math.abs(this).toFixed(f);
    
    	while ( arguments.callee.re.test(n) ) {
    		n = n.replace(arguments.callee.re, '$1,');
    	}
    
    	return (this < 0 ? '-$' : '$') + n;
    };
    
    Number.prototype.$.re = /(\d)(?=\d\d\d(?:,|\.|$))/;
    The first and second marks are used to give more flexibility in usage. If you will need to show digits after a decimal point then you can use it with no changes. The third mark is related to your question directly -- apply to the code works properly.

    Answering to your second question I can say exactly after you will give me more details on the 'G' variable -- i) what is it's value; ii) what is type of the 'G' variable; iii) where from have you got the 'G' variable?
    Last edited by siberia-man; 07-19-2011 at 10:04 AM.

  • #9
    New Coder
    Join Date
    Jul 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Siberia-Man

    Thank you once again, your tweak to the code fixed my problem of having the decimal places.

    In regards to the "G" variable.

    I have stated previously that this is a calculator app. To be more specific it's basically a quote estimator (or piece price estimator). We ask the user to input some information and then we calculate various results based upon their inputs.

    One thing we ask the user is what the annual volume of their part is. They pick a number from a drop down list and this is what my variable G is.

    Javascript to define var G:

    Code:
    var G = document.getElementById('annualvolume').value;
    var GArr=new Array("2000","3000","3500","4200","4500","6000","10000","20000");
    var GArr2=new Array("10000","30000","50000","100000","150000","300000","500000","1000000" )
    for (i in GArr)
        {
            if (G == GArr[i])
                {
                    var G2 = GArr2[i];
                }
        }
    HTML for the drop down:
    Code:
    <li data-role="fieldcontain">
        <p><span class="ui-listview-inset">Annual Volume:</label>
          <select name="annualvolume" id="annualvolume">
        
         onChange="Calculate();">
            <option value="2000">10,000</option>
            <option value="3000">30,000</option>
            <option value="3500">50,000</option>
            <option value="4200">100,000</option>
            <option value="4500">150,000</option>
            <option value="6000">300,000</option>
            <option value="10000">500,000</option>
            <option value="20000">1,000,000</option>
            </select>
        </p>
      </li>
    I hope this clarifies things for you.

    Thank you again for your help : ) It is much appreciated.

  • #10
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    I see the root of this problem. The 'G' variable is string and you tries to apply the '$' method impelememted for a numeric type. To correct the problem you can use one of the three ways.

    1. The best and simply undestandable way. Here we see that some variable 'G' (obviously it is a string variable) is converted to Number type and the '$' is called correctly.
    Code:
    ... Number(G).$() ...
    2. The second way is shorter but requires knowledge how variables are converted -- the unary plus considers any expression after itself as a number. So any string will be converted to a number even non-numeric value will be converted to a Not-A-Number value.
    Code:
    ... (+G).$() ...
    3. Multiple one will convert a string variable to a number too.
    Code:
    ... (1 * G).$() ...
    4. Call a method of one type in the context of another one. This wordy way and looks monstrously but it is very useful sometimes but not now. It is here to show that there are many ways to achieve the valid result.
    Code:
    ... Number.prototype.$.call(G) ...
    Last edited by siberia-man; 07-19-2011 at 08:52 PM.

  • #11
    New Coder
    Join Date
    Jul 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts
    siberia-man:

    You are genius man : )

    ... Number(G).$() ...
    works fines in that it adds the comma, however I don't need the "$" on this result because it's not currency.

    I apologize, I only somewhat understand how this script is working. I'm not sure how to tweak it myself to keep the comma but do away with the $ symbol.

  • #12
    Regular Coder
    Join Date
    Sep 2010
    Location
    Far far away
    Posts
    122
    Thanks
    0
    Thanked 16 Times in 16 Posts
    Heh =)

    I saw in your first post that you need convert 123456 to '$123,456' etc.

    Just replace the last line within a function with the simple return n. And keep your implementation of 'dollarize' function to insert a dollar sign before.
    Last edited by siberia-man; 07-19-2011 at 09:46 PM.


  •  

    Tags for this Thread

    Posting Permissions

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