formatter.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Formatter for number representations
  2. import round from './math';
  3. // get a fixed number of digits
  4. const fixedDigits = (number, numberDigits) => {
  5. const str = `${number}`;
  6. let padding = '';
  7. for (let i = 0; i < numberDigits; i += 1) {
  8. padding += '0';
  9. }
  10. return padding.substring(0, padding.length - str.length) + str;
  11. };
  12. const needsSpacing = (val1, val2) => {
  13. let toBeSpaced = 0;
  14. // Add additional spacing when one value has decimal places and the other not
  15. if ((val1 < 1 && val2 >= 1) || (val1 >= 1 && val2 < 1)) {
  16. toBeSpaced = 1;
  17. }
  18. return toBeSpaced;
  19. };
  20. // - 0 <= x < 1: 1 decimal place
  21. // - 1 <= x <= 100.000: 0 decimal places
  22. const getPrecision = (val) => {
  23. if (val < 1) {
  24. return 10;
  25. }
  26. return 1;
  27. };
  28. // - 0 <= x < 1: 0 spaces
  29. // - 1 <= x <= 100.000: 2 spaces
  30. const getSpacing = (val) => {
  31. if (val >= 1) {
  32. return 2;
  33. }
  34. return 0;
  35. };
  36. // - 0 <= x < 1: 1 decimal place
  37. // - 1 <= x <= 100.000: 0 decimal places
  38. const getFormattedValue = (val) => {
  39. const digits = Math.log(val) / Math.log(10);
  40. let formattedValue;
  41. if (digits < 0) {
  42. formattedValue = Math.max(round(val, 1), 0.1);
  43. } else {
  44. formattedValue = round(val, 0);
  45. }
  46. return formattedValue;
  47. };
  48. const haveSameRepresentation = (value1, value2) => {
  49. const p1 = getFormattedValue(value1);
  50. const p2 = getFormattedValue(value2);
  51. return p1 === p2 || (p1 < 0.1 && p2 < 0.1);
  52. };
  53. export {
  54. fixedDigits,
  55. needsSpacing,
  56. getPrecision,
  57. getSpacing,
  58. getFormattedValue,
  59. haveSameRepresentation
  60. };