Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * numbers.c - number formatting library
- * Copyright (C) 2019 Matteo Croce <mcroce@redhat.com>
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
- #include <stdio.h>
- #include <stdint.h>
- #include <stdlib.h>
- #include <string.h>
- #define human(x) decimals(x), rounded(x), suffix(x)
- #define H ".*f %s"
- static double rounded(uint64_t n)
- {
- if (n >= 9999500000)
- return n / 1000000000.0;
- if (n >= 9999500)
- return n / 1000000.0;
- if (n > 9999)
- return n / 1000.0;
- return n;
- }
- static int decimals(uint64_t n)
- {
- if (n >= 999950000000)
- return 0;
- if (n >= 99995000000)
- return 1;
- if (n >= 9999500000)
- return 2;
- if (n >= 999950000)
- return 0;
- if (n >= 99995000)
- return 1;
- if (n >= 9999500)
- return 2;
- if (n >= 999950)
- return 0;
- if (n >= 99995)
- return 1;
- if (n > 9999)
- return 2;
- return 0;
- }
- static char* suffix(uint64_t n)
- {
- if (n >= 9999500000)
- return "G";
- if (n >= 9999500)
- return "M";
- if (n > 9999)
- return "K";
- return "";
- }
- void removeDots(char *s) {
- int i, j, n = strlen(s);
- for (i=j=0; i < n; i++)
- if (s[i] != '.')
- s[j++] = s[i];
- s[j] = 0;
- }
- static char nums[][16] = {
- "9.999",
- "10.000",
- "99.994",
- "99.995",
- "999.949",
- "999.950",
- "9.999.499",
- "9.999.500",
- "99.994.999",
- "99.995.000",
- "999.949.999",
- "999.950.000",
- "9.999.499.999",
- "9.999.500.000",
- "99.994.999.999",
- "99.995.000.000",
- "999.949.999.999",
- "999.950.000.000",
- };
- int main(void)
- {
- uint64_t n;
- int i;
- for(i = 0; i < sizeof(nums) / sizeof(*nums); i++) {
- printf("%15s => ", nums[i]);
- removeDots(nums[i]);
- n = atol(nums[i]);
- printf("%"H"\n", human(n));
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement