次の例では、数値からスケールと精度を取得しようとしています。
var x = 1234.567;
.scale
または機能が組み込まれているのを見て.precision
いないので、それを正しくする最善の方法が何であるかわかりません。
次の例では、数値からスケールと精度を取得しようとしています。
var x = 1234.567;
.scale
または機能が組み込まれているのを見て.precision
いないので、それを正しくする最善の方法が何であるかわかりません。
以下を使用できます。
var x = 1234.56780123;
x.toFixed(2); // output: 1234.56
x.toFixed(3); // output: 1234.568
x.toFixed(4); // output: 1234.5680
var x = 1234.567;
var parts = x.toString().split('.');
parts[0].length; // output: 4 for 1234
parts[1].length; // output: 3 for 567
Javascript には、指定された長さの数値を与えるtoPrecision()メソッドがあります。
例えば:
var x = 1234.567;
x.toPrecision(4); // output: 1234
x.toPrecision(5); // output: 1234.5
x.toPrecision(7); // output: 1234.56
しかし
x.toPrecision(5); // output: 1235
x.toPrecision(3); // output: 1.23e+3
等々。
文字列に含まれていることを確認する方法はあります.
か?
var x = 1234.567
x.toString().indexOf('.'); // output: 4
.indexof()
ターゲット else の最初のインデックスを返します-1
。
別の高度なソリューション(スケールと精度の意味を正しく理解している場合):
function getScaleAndPrecision(x) {
x = parseFloat(x) + "";
var scale = x.indexOf(".");
if (scale == -1) return null;
return {
scale : scale,
precision : x.length - scale - 1
};
}
var res = getScaleAndPrecision(1234.567);
res.scale; // for scale
res.precision; // for precision
数値がfloatでない場合、関数はを返しますnull
。