hierarchical-estimates-visu.../packages/webpage-refactor/lib/truncateNums.js

40 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-06-18 03:38:06 +00:00
let topOutAt100AndValidate = (x) => {
if (x == x) {
return x > 99 ? 99 : x < 0 ? 2 : x;
} else {
return 10;
}
};
2022-06-18 18:18:15 +00:00
export const toLocale = (x) => Number(x).toLocaleString();
2022-06-18 03:20:44 +00:00
export const truncateValueForDisplay = (value) => {
2022-06-18 03:38:06 +00:00
let result;
2022-06-18 03:20:44 +00:00
if (value > 10) {
2022-06-18 03:38:06 +00:00
result = Number(Math.round(value).toPrecision(2));
2022-06-18 03:20:44 +00:00
} else if (value > 1) {
2022-06-18 03:38:06 +00:00
result = Math.round(value * 10) / 10;
} else if (value > 0) {
2022-06-18 03:20:44 +00:00
let candidateNumSignificantDigits =
2022-06-18 03:38:06 +00:00
-Math.floor(Math.log(value) / Math.log(10)) + 1;
2022-06-18 03:20:44 +00:00
let numSignificantDigits = topOutAt100AndValidate(
candidateNumSignificantDigits
);
2022-06-18 03:38:06 +00:00
result = value.toFixed(numSignificantDigits);
} else if (value == 0) {
return 0;
2022-06-18 03:38:06 +00:00
} else if (-1 < value) {
2022-06-18 03:20:44 +00:00
let candidateNumSignificantDigits =
2022-06-18 03:38:06 +00:00
-Math.floor(Math.log(Math.abs(value)) / Math.log(10)) + 1;
2022-06-18 03:20:44 +00:00
let numSignificantDigits = topOutAt100AndValidate(
candidateNumSignificantDigits
);
2022-06-18 03:38:06 +00:00
result = value.toFixed(numSignificantDigits);
} else if (value <= -1) {
result = "-" + toLocale(truncateValueForDisplay(-value));
2022-06-18 03:20:44 +00:00
} else {
2022-06-18 03:38:06 +00:00
result = toLocale(value); //return "~0"
2022-06-18 03:20:44 +00:00
}
2022-06-18 03:38:06 +00:00
return result;
2022-06-18 03:20:44 +00:00
};