Reputation: 18278
I want to clean up a whole, big JSON full of over-precise numbers.
Given numbers with both a large numbers of decimals and a great variability, such:
set 1:
w: 984.4523354645713,
h: 003.87549531298341238;
set 2:
x: 0.00023474987546783901386284892,
y: 0.000004531457539283543;
Given I want to simplify them, and store them with the same precision, let's say 4 meaningful digits, aligned on the biggest.
I want something such :
set 1:
w: 984.5,
h: 003.9;
set 2:
x: 0.0002347,
y: 0.0000045;
for all my hundreds sets and thousands numbers.
How to simplify numbers of this list while keeping n meaningful digits (aligned on the biggest) ?
Upvotes: 0
Views: 147
Reputation: 2949
Massive Edit
This function wil do what you want:
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;
}
}
}
It returns the position of the first digits you want to have, with 0 being the dot itself.
Here are some tests I ran:
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
Upvotes: 1
Reputation: 18278
See this fiddle.
// 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) );
INPUT:
w: 984.4523354645713,
h: 003.87549531298341238;
OUTPUT (nicely aligned!):
w_(rounded): 984.5,
h_(rounded): 3.9;
Upvotes: 0