1

I was looking for a JavaScript function to round a number to a specified amount of decimal places & I found this page: http://www.kadimi.com/en/round-float-349

That page includes a section that uses prototyping & the toFixed() function..... however I also found this page: http://freewebdesigntutorials.com/javaScriptTutorials/jsNumberObject/toFixedMethod.htm (see last example) & this uses the toFixed function straight up & appears to do the same thing.

I'm not a big javascript person so apologies if this is a stupid question, but what's the difference between them?

Here they are for clarity..

With prototype:

if (!Number.toFixed) {
  Number.prototype.toFixed=function(n){
    return Math.round(this*Math.pow(10, n)) / Math.pow(10, n);
  }
}

// example:
floating_number = 123.45687;
decimal_points = 2;
window.alert(floating_number.toFixed(decimal_points));

Standard:

var numex = 3.1415926535;
alert( numex.toFixed(5) );

I also tried out that first batch of code with this function..

function round_float(number,places){
    if (!number.toFixed) {
        number.prototype.toFixed=function(places){
            return Math.round(this*Math.pow(10, places)) / Math.pow(10, places);
        }
    } else {
        alert('bad');
    }
}

It went into the "bad" alert section..... I'm guessing that was caused by the false response by toFixed; any idea why this function is written like that then?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Brett
  • 19,449
  • 54
  • 157
  • 290
  • try doing `number = new Number(number)` first, then try. Forcing it to cast allows `if(number.toFixed)` to work (at least for me). (Also, the datatype is "Number" not "number" (javascript is case sensative). – Brad Christie Mar 14 '11 at 15:35
  • On a side note, `toFixed()` returns a `String`, whilst the custom implementation returns a `Number`. – pimvdb Mar 14 '11 at 15:36
  • Well, read this answer: http://stackoverflow.com/questions/661562/how-to-format-a-float-in-javascript/661757#661757 according to this `toFixed` has its problems, so having it "hard coded" is the safest way to assure it's doing what you want it to do. – Shadow The GPT Wizard Mar 14 '11 at 15:37
  • @Brad: They are int as the numbers were either put through parseInt() or parseFloat() & then just had arithmetic done on them before being passed to this function..... I even have tested it by just putting in a number & same result. – Brett Mar 14 '11 at 15:39

4 Answers4

4

Simple. Not all browsers have a toFixed so in the first example it provides a safety net. The alternative means the browser does have a toFixed which is not "bad" but "normal".

clockworkgeek
  • 37,650
  • 9
  • 89
  • 127
1

I'm not sure why you have the alert('bad') in your else block; all that really happens in the "bad" case, is that the number variable already has a member called toFixed defined (which evaluates to true when coerced to a boolean - always the case for a function).

That's not necessarily a bad thing, since this is what you want the end result to be?! The code seems to be defining a version if toFixed if there isn't already a native* implementation. The alert fires when there is native* support.

*(Well, either native to the browser or already added to the prototype by a JS library. Either way, it's already there so no more work is needed.)

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • Ahh yes I see it now. The 'bad' was just there for testing as I wasn't getting any result returned. Shouldn't there be the native function used in place of where I have my alert now then? Otherwise if there is native support for tofixed() then the function will just return nothing, no!? – Brett Mar 14 '11 at 15:45
  • @Brett - the `round_float` function that we're discussing is likely misnamed. It doesn't actually *perform* the rounding calculations; rather, it ensures that a given object (the `number` variable) has a method called `toFixed` defined on it, and creates a function to do this if one didn't exist beforehand. If it were called something like `ensureToFixedFunctionDefined` it would be clearer. (Also, the `places` argument to the method isn't used at all.) – Andrzej Doyle Mar 15 '11 at 10:17
0

I am using function for javascript toFixed() functions. In my project QA tested for unit price For example it will be 79.9989 so if i used toFixed(2) result was 80.00. In my QA does not wants toFixed with 80.00 they want 79.99

Some cases : Before after tofixed(2) 78.896 78.89 78.996 78.99

So i used my function like this:

function customtoFixed(num){
  if(num % 1 != 0){
   var split_nums = (''+num).match(/(\d+)(\.\d+)?/);
   console.log(split_nums);
      if(split_nums[2]>.995){
             return (+split_nums[1]) + (+0.99);
      } else {
      return num.toFixed(2); 
      }
   } else {
    return num.toFixed(2); 
   }
}
karthik
  • 1
  • 1
0

I would try something like this:

if (!Number.toFixed){
    Number.prototype.toFixed = function(n){
        return Math.round(this * Math.pow(10, n)) / Math.pow(10, n);
    }
}

var num = 123.4567;
$('body').append(num.toFixed(3));

Perform the "Existence check" before you need it, and not within the function. (Confirmed to work)

Brad Christie
  • 100,477
  • 16
  • 156
  • 200