2010-05-19 2 views
5

Я видел this format function ссылается на несколько сайтов, но ни один из них не имеет явного примера того, как передать число в функцию.Пройденный номер, Number.prototype.format

Я пробовал '12345'.формат (' 0,00 '), который, как я считаю, должен быть написан, но он дает мне ошибку, что объект не поддерживает свойство или метод. Я также попробовал Number ('12345'). Format ('0.00'); var num = '12345' // num.format ('0.00'); format ('0.00', '12345') и даже попытались использовать числа вместо строк 12345.format (0.00). Я пропустил что-то действительно очевидное здесь?

Включенная копия функции для справки, поэтому вам не нужно заходить на сайт (со всеми заполненными фрагментами).

/** 
* I ♥ Google 
*/ 
String.prototype.stripNonNumeric = function() { 
    var str = this + ''; 
    var rgx = /^\d|\.|-$/; 
    var out = ''; 
    for(var i = 0; i < str.length; i++) { 
     if(rgx.test(str.charAt(i))) { 
      if(!((str.charAt(i) == '.' && out.indexOf('.') != -1) || 
      (str.charAt(i) == '-' && out.length != 0))) { 
       out += str.charAt(i); 
      } 
     } 
    } 
    return out; 
}; 

/** 
* Formats the number according to the 'format' string; adherses to the american number standard where a comma is inserted after every 3 digits. 
* note: there should be only 1 contiguous number in the format, where a number consists of digits, period, and commas 
*  any other characters can be wrapped around this number, including '$', '%', or text 
*  examples (123456.789): 
*   '0' - (123456) show only digits, no precision 
*   '0.00' - (123456.78) show only digits, 2 precision 
*   '0.0000' - (123456.7890) show only digits, 4 precision 
*   '0,000' - (123,456) show comma and digits, no precision 
*   '0,000.00' - (123,456.78) show comma and digits, 2 precision 
*   '0,0.00' - (123,456.78) shortcut method, show comma and digits, 2 precision 
* 
* @method format 
* @param format {string} the way you would like to format this text 
* @return {string} the formatted number 
* @public 
*/ 
Number.prototype.format = function(format) { 
    if (!(typeof format == "string")) {return '';} // sanity check 

    var hasComma = -1 < format.indexOf(','), 
     psplit = format.stripNonNumeric().split('.'), 
     that = this; 

    // compute precision 
    if (1 < psplit.length) { 
     // fix number precision 
     that = that.toFixed(psplit[1].length); 
    } 
    // error: too many periods 
    else if (2 < psplit.length) { 
     throw('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format); 
    } 
    // remove precision 
    else { 
     that = that.toFixed(0); 
    } 

    // get the string now that precision is correct 
    var fnum = that.toString(); 

    // format has comma, then compute commas 
    if (hasComma) { 
     // remove precision for computation 
     psplit = fnum.split('.'); 

     var cnum = psplit[0], 
      parr = [], 
      j = cnum.length, 
      m = Math.floor(j/3), 
      n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop 

     // break the number into chunks of 3 digits; first chunk may be less than 3 
     for (var i = 0; i < j; i += n) { 
      if (i != 0) {n = 3;} 
      parr[parr.length] = cnum.substr(i, n); 
      m -= 1; 
     } 

     // put chunks back together, separated by comma 
     fnum = parr.join(','); 

     // add the precision back in 
     if (psplit[1]) {fnum += '.' + psplit[1];} 
    } 

    // replace the number portion of the format with fnum 
    return format.replace(/[\d,?\.?]+/, fnum); 
}; 

ответ

1

Это не полный код - отсутствует isType и stripNonNumeric методы. Но в любом случае, так как это расширение на номер объектов себя, вы можете использовать его как:

(42).format('0.00'); 

или

var a = 42; 
a.format('0.00'); 

'12345'.format('0.00') не будет работать, как '12345' здесь является строкой, но этот метод был определен только для номера.

Для этого необходимо указать номер в круглых скобках и способы, которыми вы можете пройти мимо него, не используя их, хотя я бы не рекомендовал его - из-за всех этих слухов об обслуживающих программистах и ​​топорах и т. Д. Я не говорю, что каждый инженер-программист носит один в своем рюкзаке, но зачем рисковать. Они любят взломать тоже, но не с кодом. Hahahaha

+1

На самом деле вам не нужно вставлять число в круглые скобки - вам просто нужно оставить пробел между номером и точкой. Таким образом, интерпретатор не воспринимает точку как разделитель дробей, а как точечный оператор. '42 .format ('0.00')' – Andris

+0

Да, но мне это не нравится :) См. Прикрепленный вопрос - http://stackoverflow.com/questions/2726590/call-methods-on-native-javascript-types - без обертывания - для получения дополнительной информации об этом. – Anurag

+0

Я заметил, что он был неполным после повторного рассмотрения. Я не понимаю, как так много людей в сети утверждали, что это сработало для них ... но так или иначе, вы совершенно ясно ответили на мой основной вопрос. Благодаря! Жаль, что я не могу заставить функцию работать. – Choy

Смежные вопросы