-2

I should to cut the value to int and float parts. Like '21' - want to get '2' and '1' as ints.

float fp; // float part
float fp1; // new "int-style" float part
float ip; // int part

fp = modff(21.0/10, &ip);
ip = ip*10; // there i will get the '2'. Its works fine
fp1 = fp*10; // there i will get a null (0.09999999 by debugger, 
but should to be 0.99+)... 

But with any other value, '22' for instance, it is will work. fine also. Whats wrong? :(

Seems like this function doesn't like the unit

==================================

Yeah easy fixed! :) I used 'modf' instead of 'modff'. It has 'double' datatype, so it works fine now )

Thanks for the answers

FireForce
  • 23
  • 6
  • 1
    `21` doesn't have a fractional part. It will give `21` integral part and `0` fractional part. I don't understand your question. – interjay May 22 '13 at 14:06
  • interjay> I wan't to get the '21' as '2' and '1'. I have converted '21' to '2.1' before rest operations. Ah sorry, my fault. Forgot to note the '21.0/10' – FireForce May 22 '13 at 14:09
  • Please post some code **that you have tested**, and say what it outputs and what you expected. You obviously haven't tested the code posted here because you keep editing it to fix errors. – interjay May 22 '13 at 14:14
  • I'll notice it, sorry – FireForce May 22 '13 at 14:17
  • So you want to break a `float` apart into its place values and save each as an `int`? Such as converting `374` to `3`, `7`, and `4`? It looks like one of the problems you may be having is [floating point inaccuracies](http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples). – Reinstate Monica -- notmaynard May 22 '13 at 14:19
  • Yeah. As i already said, my way works with any x2 values (22,23,24+ etc), but doesn't work with '21' with strange reason... – FireForce May 22 '13 at 14:21
  • Search (on this site or Google) for "floating point arithmetic," "floating point inaccuracy," etc. The problem is with the way floats represent the decimal value of `2.1` and many other numbers. It's kind of a thick subject, but it's necessary to understand at least the basics of why it works as it does. Someone else who understands it better may be able to give you a good quick explanation for your particular problem. – Reinstate Monica -- notmaynard May 22 '13 at 14:26
  • Thank you for the answ^^. Im gone to searching about it ) – FireForce May 22 '13 at 14:28

1 Answers1

1

In floating point, when you do 21.0 / 10.0 you generally dont get 2.1. What you get is 2.099 or something like that due to floating point inaccurancy.

float fp; // float part
float fp1; // new "int-style" float part
float ip; // int part

float value = 21.0;
float part = 10.0;
fp = modf(value / part, &ip);
fp1 = value - (ip * part); //gives you 21 - (2 * 10) = 1

//ip = 2
//fp1 = 1
Martin Perry
  • 9,232
  • 8
  • 46
  • 114