-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloatToString.c
98 lines (85 loc) · 1.69 KB
/
floatToString.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"
/**
* floatToString - Converts a floating-point number
* to a dynamically allocated string.
*
* @number: The floating-point number to be converted to a string.
*
* Description:
* This function takes a floating-point number and
* converts it into a dynamically
* allocated string. The resulting string
* contains the floating-point number in
* string format.
* Return: char charchter
*/
char *floatToString(float number)
{
/* Declare variables */
char *result;
int integerPart;
float fractionalPart;
int decimalPlaces = 6; /* You can adjust the number of decimal places */
int power;
int i = 0;
int j;
int start = 1;
int end = i - 1;
result = (char *)malloc(64);
if (result == NULL)
{
return (NULL); /* Memory allocation failed */
}
/* Handle the sign */
if (number < 0)
{
result[0] = '-';
number = -number;
}
else
{
result[0] = ' ';
}
/* Convert the integer part to a string */
integerPart = (int)number;
i = 1; /* Start index for the string */
if (integerPart == 0)
{
result[i++] = '0';
}
else
{
while (integerPart > 0)
{
result[i++] = '0' + (integerPart % 10);
integerPart /= 10;
}
/* Reverse the integer part in the string */
while (start < end)
{
char temp = result[start];
result[start] = result[end];
result[end] = temp;
start++;
end--;
}
}
/* Add the decimal point */
result[i++] = '.';
/* Convert the fractional part to a string */
fractionalPart = number - (float)integerPart;
power = 1;
for (j = 0; j < decimalPlaces; j++)
{
int digit = (int)(fractionalPart *power);
power *= 10;
result[i++] = '0' + (digit % 10);
fractionalPart *= power;
}
/* Null-terminate the string */
result[i] = '\0';
return (result);
}