6

次の例では、数値からスケールと精度を取得しようとしています。

var x = 1234.567;

.scaleまたは機能が組み込まれているのを見て.precisionいないので、それを正しくする最善の方法が何であるかわかりません。

4

3 に答える 3

6

以下を使用できます。

var x = 1234.56780123;

x.toFixed(2); // output: 1234.56
x.toFixed(3); // output: 1234.568
x.toFixed(4); // output: 1234.5680
于 2015-11-25T14:45:10.733 に答える
5
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

于 2012-06-08T16:48:33.307 に答える
4

別の高度なソリューション(スケール精度の意味を正しく理解している場合):

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

于 2012-06-08T16:58:44.690 に答える