質問

JavaScriptを使用して10進数を6桁に丸める必要がありますが、できるNumber.toFixedに依存しない

  

toExponential、toFixed、toPrecisionの大きな問題は、Firefoxバージョン1.5まではMozillaでサポートされていなかった(IEはバージョン5.5以降のメソッドをサポートしていましたが)かなり現代的な構成であるということです。これらのメソッドを使用することはほとんど安全ですが、古いブラウザは壊れるので、公開プログラムを作成する場合は、古いブラウザにこれらのメソッドの機能を提供する独自のプロトタイプを提供することをお勧めします。

次のようなものの使用を検討しています

Math.round(N*1000000)/1000000

これを古いブラウザにプロトタイプを提供する最良の方法は何ですか?

役に立ちましたか?

解決

これを試してください:

if (!Number.prototype.toFixed)

    Number.prototype.toFixed = function(precision) {
        var power = Math.pow(10, precision || 0);
        return String(Math.round(this * power)/power);
    }

他のヒント

Firefox 1.5とIE 5はほとんど使われていないか、ごく少数の人々が使用していると思います。
Netscape Navigatorをサポートするコーディングに少し似ています... :-)
他の主要なブラウザー(Opera?Safari?可能性が低い...)がこれをサポートしていない場合、またはWebログに多くのレガシーブラウザーの使用が示されている場合は、おそらくこれらの方法を使用できます。
いつか先に進まなければなりません。 ^ _ ^

[編集] Opera 9.50およびSafari 3.1で正常に動作します

javascript: var num = 3.1415926535897932384; alert(num.toFixed(7));

あなたが参照する記事は1年半前のIT業界の永遠です... IEユーザーとは異なり、Firefoxユーザーは最新バージョンに行くことが多いと思います。

Bytesウェブサイトから、この関数はセルジュllinskyのものとほぼ同じ:

if (!num.toFixed) 
{
  Number.prototype.toFixed = function(precision) 
  {
     var num = (Math.round(this*Math.pow(10,precision))).toString();
     return num.substring(0,num.length-precision) + "." + 
            num.substring(num.length-precision, num.length);
  }
}

別のオプションは(不必要に文字列に変換せず、(162.295).toFixed(2)の計算ミスを162.29(162.30である必要があります)に修正します。

Number.prototype._toFixed=Number.prototype.toFixed; //Preserves the current function
Number.prototype.toFixed=function(precision){
/* step 1 */ var a=this, pre=Math.pow(10,precision||0);
/* step 2 */ a*=pre; //currently number is 162295.499999
/* step 3 */ a = a._toFixed(2); //sets 2 more digits of precision creating 16230.00
/* step 4 */ a = Math.round(a);
/* step 5 */ a/=pre;
/* step 6 */ return a._toFixed(precision);
}
/*This last step corrects the number of digits from 162.3 ( which is what we get in
step 5 to the corrected 162.30. Without it we would get 162.3 */

編集:この特定の具体化を試みると、 this * = Math.pow(10、precision || 0)は、無効な左辺の割り当てエラーを作成します。このキーワードに変数 a を与えました。関数を閉じた場合にも役立ちます^ _ ^ ;;

これを試してください:

 Number.prototype.toFixed = function(precision) {
     var power = Math.pow(10, precision || 0);
     return String(Math.round(this * power)/power);
 }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top