Page 1 of 1

Float and three decimal places

Posted: Sun Dec 03, 2017 1:47 pm
by palikem
Hello.

There is a possibility that the float variable has three decimal places ?

Re: Float and three decimal places

Posted: Sun Dec 03, 2017 2:59 pm
by doublemax
Please provide some more context. The internal representation of a float and how you display it are two separate things. You can limit the number of visible decimal places with a typical printf format string.

https://en.wikipedia.org/wiki/Printf_format_string

Re: Float and three decimal places

Posted: Sun Dec 03, 2017 3:39 pm
by palikem
I need to compare them.
One is fixed and the other is the cycle for ().
While I have addressed it through pomocny int, it is unnecessarily complicated

Re: Float and three decimal places

Posted: Sun Dec 03, 2017 4:24 pm
by doublemax
Sorry, i don't understand.

What exactly do you need to do? Can you give an example?

Re: Float and three decimal places

Posted: Sun Dec 03, 2017 4:47 pm
by palikem
One is the logarithmic axis

Code: Select all

float a, b, c;

b = 1.0;
c = 0.1;

for(a=0.1; a<=100.0; a=a+c){
	if(a == b){
		b = b * 10.0;
		c = c * 10.0;
	}
	//I am interested in the variable "a" which should be  0.1, 0.2, 0.3~1.0  1.0, 2.0, 3.0~10.0  10.0, 20.0, 30.0~100.0
}

Re: Float and three decimal places

Posted: Sun Dec 03, 2017 5:03 pm
by doublemax
Comparing float values for equality is tricky and should be avoided. In your case i'd just use a separate integer that determines when to change the "step" value.

Re: Float and three decimal places

Posted: Sun Dec 03, 2017 5:16 pm
by palikem
I had it as a plan B.

Thank you doublemax

Re: Float and three decimal places

Posted: Sun Dec 03, 2017 5:57 pm
by eranon
Easiest way to compare two floats for "sure":

Code: Select all

bool compare_float(double x, double y)
{
   // Easy way to compare two floating point numbers a safer way than using "=="
   // IN : two floats to compare
   // OUT : true:equals, false:differents
   // REF: http://www.drdobbs.com/cpp/its-hard-to-compare-floating-point-numbe/240149806
   // NB: more sophisticated way to consider if needed:
   //     https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
   if (isnan(y))
      return !isnan(x);
   return x < y;
}
However, as doublemax stated, the internal representation of a float is variable, undefined and unpredictable (hardware, context dependent) and is not limited to three decimal places even when you represent it like this on screen through printf or its wxWidgets equivalent wxString::Format.