# How to round to the left of the decimal?

Most topics are asking about how to round to the right of the decimal, but I want to round to the nearest tens place instead, if that's possible. I'm using the tutorial Arduino Knob, but the servo is jumping from every small change, and I want to round my final value to reduce the jumping as much as possible.

Hi.
Divide the number by 10, do it round and multiply by 10.

RV mineirin

Arendodently?

Sorry,
round

I would add 5 before dividing by 10, else the result is floored instead of rounded
`int result = ( ( number + 5 ) / 10 ) * 10`

It didn't round my variable, BUT somehow it made the numbers jump less erratically, and it works fluently!

What do you mean ? Which type is your variable ? This code will work only for positive integers (as returned by analogRead)

``````#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = 0;  // analog pin used to connect the potentiometer
int val = 0;    // variable to read the value from the analog pin
int pot = 0;

void setup() {
myservo.attach(9);  // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
}

void loop() {
pot = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
val = ( ( pot + 5 ) / 10 ) * 10;
val = map(val, 600, 1020, 50, 180);  // scale it to use it with the servo (value between 0 and 180)
myservo.write(val);                  // sets the servo position according to the scaled value
Serial.println(val);
delay(0);                           // waits for the servo to get there
}
``````

The new code using the script you sent

Do it after map()

And your map() will return negative numbers so code need to be slightly modified.

Try:

``````val = map(pot, 600, 1020, 50, 180);
val = ( ( val + ( val > 0 ? 5 : -5 ) ) / 10 ) * 10;
``````

Yup, works now!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.