I have a function which should covert a double value into string one:
inline static string StringFromNumber(double val) // suppose val = 34.5678
{
long integer = (long)val; // integer = 34
long pointPart; // should be = 5678 how do I get it?
}
How do I get a long value for both integer and pointPart?
Add: I want a precision of 17 numbers, with discarding the zeros. More examples:
val = 3.14 integer = 3 pointPart = 14
val = 134.4566425814748 integer = 134 pointPart = 4566425814748
I have not got any solution so far. How can I get it?
You can use
modfto separate the integer and fractional parts. You can then multiply the fractional part by1.0e17, and callfloorto properly round the results to it’s integer component, and then cast to aunsigned long(the fractional part will never be negative, and this allows you to maximize the number of bits in the integral type). Finally run though a loop to trim off the zeros on theunsigned long. For instance:Note that this code will only work up to 17 decimal places if you are on a 64-bit platform and
unsigned longis defined as a 64-bit integer-type. Otherwise you will want to changeunsigned longtouint64_t. Also keep in mind that since floating point numbers are approximations, and there’s a multiplier by1.0e17, the value offracpartmay not be exactly the value of the point-part ofval… in other words there may be some additional digits after any necessary rounding.