summaryrefslogtreecommitdiff
path: root/tests/cpp/include/doubl2str.h
blob: 1a5e3fc817afecd83c4ae9e0410efaf4aeb5365b (plain)
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
99
100
101
102
/**
 *
 *  double -> string
 *
 */



char num2char(unsigned int num) 
{
	switch(num)
	{
	    case 0:
	        return '0';
	    case 1:
	        return '1';
	    case 2:
	        return '2';
	    case 3:
	        return '3';
	    case 4:
	        return '4';
	    case 5:
	        return '5';
	    case 6:
	        return '6';
	    case 7:
	        return '7';
	    case 8:
	        return '8';
	    case 9:
	        return '9';
	}

	//return '\0';
	return '-';
}

std::string double2str(long double D)
{
	int sign = (D > 0) ? 1 : (D*=-1.0, -1);
	unsigned long long int Ceil = D;
	
	// if D is ceil
	if(Ceil == D)
	{
		return std::to_string( (long long)(D*sign) );
	}

	// size of result buffer
	const int bs = 32;
	
	// size of temporary buffer
	const int pw = 16;
	// Temporary buffer
	char buf[pw];
	// Result buffer
	char rez[bs];

	int i, size = 0;
	// set sign
	if(sign < 0) rez[size++] = '-';

	// set ceil
	std::string sceil = std::to_string(Ceil);
	const char * bceil = sceil.c_str();
	int sceillen = sceil.size();
	for(i = 0; i < sceillen; i++)
	{
		rez[size++] = bceil[i];
	}

	// set point
	rez[size++] = '.';
	
	unsigned long long int I =  D * 10000000000000000; // D * 10**pw
	// .14159265359 -> 14159265359000000
	I -= Ceil * 10000000000000000;

	// Remove the tail of zeros
	// 14159265359000000 -> 14159265359
	while(0 == I % 10) I /= 10;

	int ind = 0;
	while(I > 0)
	{
		buf[ind++] = num2char(I%10);
		I = (I - I%10) / 10;
	}

	// set fraction part
	for(i = 0; i < ind; i++)
	{
		rez[size] = buf[ind-i-1];
		size++;
	}

	return std::string(rez, size);
	//rez[size] = '\0';
}