1362Views3Replies

Author Options:

How to get rid of decimals or add them? Answered

So here's my code.

void loop()
{
  int pot = analogRead(A0);
  float xval = pot * (10.0 / 1023.0);
  Serial.println(xval);
}

When I open up serial monitor, I get a number (1-10 depending on my potentiometer) and two decimals. How do I make go in whole number increments? 1, 2, 3, etc? Can you show me the code and explain it?

Also, here's another example

centimeters = (xval * 2.54);
Serial.print(centimeters);

In this example, I only get a whole number. Can somebody show me some code to make it show decimals? Explain some code?

Thanks!

3 Replies

user
bwrussellBest Answer (author)2013-03-07

xval is a float data type which has a floating decimal point. If you want whole values only you need to use and int type.

In the second version you probably initiated xval as an int.

Select as Best AnswerUndo Best Answer

user
HavocRC (author)bwrussell2013-03-07

Oh bwrussel thanks so much! It just hit me!

So if I type in
float xval = ... then it will be a decimal
If I type in
int xval = . . . then it will be a whole number.

And yes, in my other project, I did put initiate them in the beginning of the sketch. Thank you so much!

Select as Best AnswerUndo Best Answer

user
steveastrouk (author)2013-03-07

Use the "printf" statement to adjust the format, and "ceil" and "floor" to clip the number to an integer.

Select as Best AnswerUndo Best Answer