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 回答