dooooooduo

Double precision str

Dec 7th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.77 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. int main(void) {
  6.     char  *str     = (char *) malloc(sizeof(char *));
  7.     int    offset  = 0;
  8.     double num     = 123456.00001;
  9.     int    num_int = (int) num;
  10.     double decimal = num - num_int;
  11.     int    digits  = 0;
  12.  
  13.     if (num < 0) {
  14.         str[offset++] = '-';
  15.     }
  16.    
  17.     while (num_int) {
  18.         digits++;
  19.         num_int /= 10;
  20.     }
  21.    
  22.     for (int i = digits - 1; i >= 0; i--) {
  23.         str[offset++] = '0' + (((int) (num / pow(10, i))) % 10);
  24.     }
  25.    
  26.     if (decimal) str[offset++] = '.';
  27.  
  28.     while (decimal) {
  29.         decimal       *= 10;
  30.         str[offset++]  = '0' + (int) decimal;
  31.         decimal        = decimal - (int) decimal;
  32.     }
  33.  
  34.     str[offset] = '\0';
  35.     printf("num       : %f\n", num);
  36.     printf("actual_num: %s\n", str);
  37.  
  38.     return 0;
  39. }
Add Comment
Please, Sign In to add comment