Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

alternative to toFixed returns weird result

Status
Not open for further replies.

EwS

Programmer
Dec 30, 2002
398
US
I came across different posts that talk about alternatives to toFixed, which doesn't work in Safari. However, I didn't find a solution that would really work for me - I don't want to hardcode any decimal places, I want to pass it as an argument to a function. And I found a function on another site, which supposed to work on both Explorer and Safari; the thing is that it does work in Explorer (returns '300.00'), but in Safari I get this weird result: '300function pad(s) { s= s || "."; return s.length > n ? s : pad(s+"0");'

This is the function definition:
Code:
Number.prototype.toDecimals=function(n){
    n=(isNaN(n))?
        2:
        n;
    var nT=Math.pow(10,n);
    function pad(s){
            s=s||'.';
            return (s.length>n)?
                s:
                pad(s+'0');
    }
    return (isNaN(this))?
        this:
        (new String(
            Math.round(this*nT)/nT
        )).replace(/(\.\d*)?$/,pad);
}

This is how I call the function:
Code:
var myNumber=300, formattedNumber=myNumber.toDecimals(3);
 
Sorry, I made a typo - the correct result from Explorer is '300.000', not '300.00'.
 
This works (you just pass the name of the text box and number of decimal places):

Code:
// Format the input 
//
formatNumeric(document.myForm.myTextBox,3);

function formatNumeric(t,decimal) {
  // verify the input is numeric
  if (isNaN(t.value)) {
    t.value = "0";
  }
  var nT=Math.pow(10,decimal);
  var sValue = Math.round(t.value * nT) + "";
  if (sValue == 0) {
    sValue = pad(decimal+1,t.value.toString(),'0');    
  }
  a = new Array();
  a = sValue.split(".");

  // there's already a decimal point in the string
  if (a.length == 2) { 
    return;
  }

  var sPart1 = sValue.substr(0, sValue.length-decimal);
  var sPart2 = sValue.substr(sValue.length-decimal);
  var s = sPart1+"."+sPart2;
  t.value = s;
}


// Pad a string
//
function pad(length,string,filler) {
  if (length <= string.length) {
    return string;
  }
  max = length - string.length;

  for (var i = 0; i < max; i++)  {
    string += filler;
  }
  return string;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top