0

過度に正確な数値でいっぱいの大きな JSON 全体をクリーンアップしたいと考えています。

次のように、多数の小数と大きな変動性の両方を持つ数値を指定します。

set 1:
w: 984.4523354645713, 
h: 003.87549531298341238;

set 2:
x: 0.00023474987546783901386284892,
y: 0.000004531457539283543;

それらを単純化し、同じ精度で保存したい場合は、意味のある4桁を最大に並べてみましょう。

私はそのようなものが欲しい:

set 1:
w: 984.5,
h: 003.9;

set 2:
x: 0.0002347,
y: 0.0000045;

私の何百ものセットと何千もの数字のために。

n の意味のある数字を維持しながら、このリストの数字を単純化する方法 (最大に揃える) ?

4

2 に答える 2

1

大規模な編集

この関数は、あなたが望むことを行います:

function get_meaningful_digit_pos(digits, val1, val2) {
    var max = Math.max.apply(null, [val1, val2].map(function(n) {
            return Math.abs(n);
        })),
        digit = Math.pow(10, digits),
        index = 0;

    // For positive numbers, check how many numbers there are
    // before the dot, then return the negative digits left.
    if (max > 0) {
        while (digit > 1) {
            if (max >= digit) {
                return -digits;
            }

            digits--;
            digit /= 10;
        }
    }

    // Loop 15 times at max; after that in JavaScript a double
    // loses its precision.
    for (; index < 15 - digits; index++) {
        if (0 + max.toFixed(index) !== 0) {
            return index + digits;
        }
    }
}

必要な最初の数字の位置を返します。0 はドット自体です。

ここに私が実行したいくつかのテストがあります:

get_meaningful_digit_pos(4, 1234, 0.0);          // -3
get_meaningful_digit_pos(4, 12.000001234, 0.0);  // -1
get_meaningful_digit_pos(4, 1.234, 0.0);         // 0
get_meaningful_digit_pos(4, 0.1234, 1.0);        // 0
get_meaningful_digit_pos(4, 0.0000001234, 0.0);  // 7
get_meaningful_digit_pos(4, 0.0000001234, 10.0); // -1
于 2013-09-26T18:34:42.793 に答える
0

このフィドルを参照してください。

// create our list:
var width  = 984.4523354645713,
    height = 003.87549531298341238;
// pick the biggest:
var max = Math.abs( Math.max( width, height) );
// How many digits we keep ?
if      ( max < 10000&& max >= 1000 ) { digits = 0; } 
else if ( max < 1000 && max >= 100  ) { digits = 1; }
else if ( max < 100  && max >= 10   ) { digits = 2; }
else if ( max < 10   && max >= 1    ) { digits = 3; }
else if ( max < 1    && max >= 0.1  ) { digits = 4; }
else if ( max < 0.1  && max >= 0.01 ) { digits = 5; }
else if ( max < 0.01  && max >= 0.001){ digits = 6; };
// Simplify accordingly:
console.log("w: " + width + ", h: "+ height +", w_(rounded): "+ width.toFixed(digits) +", and h_(rounded): " + height.toFixed(digits) );

入力:

w: 984.4523354645713, 
h: 003.87549531298341238; 

出力 (きれいに整列!):

w_(rounded): 984.5, 
h_(rounded):   3.9;
于 2013-09-26T18:29:17.343 に答える