3 Replies Latest reply on Jun 3, 2010 9:19 AM by Harbs.

    changing the formatting of a number

    Mickeske Level 1

      hey,

       

       

       

      working javascript CS4 with number with a lot of numbers behind the decimal isn't easy.

      But i can't find anything how can change this...

       

      ex: 12,248481545454 should be 12,25...

       

      help...

        • 1. Re: changing the formatting of a number
          Kasyan Servetsky Level 5

          var number = 12.248481545454;
          number.toFixed(2);

          • 2. Re: changing the formatting of a number
            Shonkyin Level 3

            var number = 12.248481545454;
            number.toFixed(2);

             

            Result of above code comes 12.24

             

            But if you want 12.25 then use below code

             

            var number = 12.248481545454;
            alert(roundToDP (number ,2))
            
            function roundToDP (val,dig)
            {
                 // Including all its zeros, lopping off beyond:
                 val = Math.round(val*Math.pow(10,dig));
                 // Force in decimal point at the right place:
                 val = String(val);
               //  return val.slice(0,val.length-dig)+"."+val.slice(dig);
                 return val.slice(0,val.length-dig)+"."+val.slice(val.length-dig);
            }
            

             

             

            Shonky

            • 3. Re: changing the formatting of a number
              Harbs. Level 6


              WOW!

               

              And I would have done:

              var number = Math.round(12.248481545454*100)/100;

               

              Or in function form:

               

              var number = RoundWithDecimal(12.248481545454,2);
              
              function RoundWithDecimal(number,decimals){
                  var multiplier = Math.pow(10,decimals);
                  return Math.round(number*multiplier)/multiplier;
              }
              
              

               

              Harbs