www.webdeveloper.com
Results 1 to 9 of 9

Thread: two decimal places

  1. #1
    Join Date
    Mar 2010
    Posts
    6

    two decimal places

    Hi,

    I am new to javascript and I am attempting to output to two decimal places as its currency.

    As an example it currently outputs as 127.1 instead of 127.10.

    Can anyone look at the snippet of code and show me how please?

    function fixNums(value)
    {

    var raise = Math.pow(10,2);



    value = Math.round(value * raise) / raise;
    return value;

    }



    function calcCost(frm)
    {

    var totalArea = ((frm.area1width.value * frm.area1length.value);

    var totalCostSand = totalArea * sandCost;

    frm.totalCostSand.value =fixNums(totalCostSand);
    }


    <p style="text-align: right;">cost for sanding
    <input name="totalCostSand" type="text" class="input" style="width: 50px;" readonly="readonly" />
    </p>


    thanks

  2. #2
    Join Date
    Feb 2006
    Posts
    2,926
    use number.toFixed(decimals)
    Code:
    function calcCost(frm){
        var totalCostSand=  frm.area1width.value*frm.area1length.value*sandCost;
        frm.totalCostSand.value= totalCostSand.toFixed(2);
    }

  3. #3
    Join Date
    Mar 2010
    Posts
    6
    many thanks

  4. #4
    Join Date
    Dec 2008
    Posts
    488
    Important note: number.toFixed(decimal places | integer) returns a string.

  5. #5
    Join Date
    Mar 2010
    Posts
    6
    Quote Originally Posted by jamesbcox1980 View Post
    Important note: number.toFixed(decimal places | integer) returns a string.
    Ah so if I wanted to pass the result to a shopping cart then it could cause me problems then?

  6. #6
    Join Date
    Feb 2006
    Posts
    2,926
    You are using the string as a form field value-all form field values are strings.
    The server (presumably) will convert it to a number.

  7. #7
    Join Date
    Mar 2010
    Posts
    6
    Thanks for clearing that up

  8. #8
    Join Date
    Dec 2008
    Posts
    488
    Yeah you should be fine. mrhoo said it best. I just wanted you to keep that in mind in case you decided to use it in math somewhere else. I remember running into an issue with that along time ago thinking that it returned a number as a se point variable.

  9. #9
    Join Date
    Mar 2010
    Posts
    6
    thanks for the heads up

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles