(cls, num, metric=False, precision=1)
| 1864 | |
| 1865 | @classmethod |
| 1866 | def format(cls, num, metric=False, precision=1) -> str: |
| 1867 | assert isinstance(precision, int) and precision >= 0 and precision <= 3, "precision must be an int (range 0-3)" |
| 1868 | unit_labels = cls.METRIC_LABELS if metric else cls.BINARY_LABELS |
| 1869 | last_label = unit_labels[-1] |
| 1870 | unit_step = 1000 if metric else 1024 |
| 1871 | unit_step_thresh = unit_step - cls.PRECISION_OFFSETS[precision] |
| 1872 | |
| 1873 | is_negative = num < 0 |
| 1874 | if is_negative: |
| 1875 | num = abs(num) |
| 1876 | if num < unit_step: # return exact bytes when size is too small |
| 1877 | return cls.PRECISION_FORMATS[0].format('-' if is_negative else '', num, unit_labels[0]) |
| 1878 | for unit in unit_labels: |
| 1879 | if num < unit_step_thresh: |
| 1880 | break |
| 1881 | if unit != last_label: |
| 1882 | num /= unit_step |
| 1883 | return cls.PRECISION_FORMATS[precision].format('-' if is_negative else '', num, unit) |
no outgoing calls