If you have a float in the form A.CDEFGHI, how do you truncate the end to only have three numerals: A.CD ?
For example: I want to convert 3.5123444 to 3.51.
If you have a float in the form A.CDEFGHI, how do you truncate the end to only have three numerals: A.CD ?
For example: I want to convert 3.5123444 to 3.51.
First, I am not trying to stir the pot, as it were; nor do I mean any offense.
What exception would there be?
@MT: It depends on the arguments supplied, -3.18 for instance, floors to -3.2, and truncates to -3.1. FLOOR does truncate and is equivalent to TRUNC on positive arguments, CEIL is equivalent to TRUNC on negative arguments, but what each of these functions truncates towards is the important distinction. Floor truncates toward negative infinity, CEIL truncates toward positive infinity, and actual TRUNC functions truncate toward zero. Using these functions interchangeably (without knowing for sure if you are dealing with exclusively positive digits) will produce inaccurate results.
@Yeldarb: I was simply saying it is more accurate to use the full precision number for operations, and only to truncate the displayed number. Obviously if NeoDreamer wants to do calculations with a truncated number, they should use a truncated number.
I retract my statement that floor doesn’t truncate, I don’t know why I said that.
I’m not sure but I think that behavior is undefined in the C++ spec (in terms of truncation on integer division); it may be compiler/processor dependent.
It could very well be compiler specific (VS2005 Pro on my end). The funny part about this discussion is that there really is no trunc function inherent to C++, so one would most likely be relegated to using float or ceil in a conditional (negative or positive) like this:
double fakeTRUNC(double n, double p = 1)
{
if(n > 0)
{
double val = (pow(10,p)) * n;
floor(val);
val /= pow(10,p);
return val;
}
else
{
double val = (pow(10,p)) * n;
ceil(val);
val /= pow(10,p);
return val;
}
}
But here is a trunc function that uses modf to actually truncate:
double TRUNC(double value, int decimal_places)
{
double integer = 0,
fractional = 0,
output = 0;
int j = 0,
places = 1;
fractional = modf(value, &output);
for( int i = 0; i < decimal_places + 1; i++ )
{
fractional = modf(fractional, &integer);
for( j = 0; j < i; j++ )
{
places *= 10;
}
output += integer / places;
places = 1;
fractional *= 10;
}
return output;
}
Haven’t tried it, but perhaps just an integer type conversion could help?
float pi = 3.1415926;
float pi2 = (float)((int)(pi*100)/100);
(The above may be incorrect, but the point is to create an integer with two extra decimals, and it will simply discard anything after the floating point - just reverse it again, and you would have a truncated number)
:: Copyright KIRUPA 2024 //--