# [SOLVED]How to do integer divison rounding to closest integer, vhdl synthesizable code?

Status
Not open for further replies.

#### nicklas_a74

##### Member level 1
Hi

I want to have generic input values e.g. a and b what are used to initialize a
constant by e.g. constant c:= a/b; However due to the division the
correct answer could be 4.6 but it’s rounded down to closest integer 4 as default.
How to being able to initialize the c and have a rounding to closest integer 5?
The code should be synthesizable and use the standard libraries. Is there a
way to do this without fixedpoint or special math library?

Try c:= a/b + 0.5;
It can be more complicated if negative values are involved.

• nicklas_a74

### nicklas_a74

Points: 2
The simple trick is to add half the divisor to the dividend before doing the division.

So basically you should do c:= ( a + b/2 ) / b

• nicklas_a74

### nicklas_a74

Points: 2
If it is only a generic or constant, you can use the real type:

c := integer( real(a)/real(b) );

real -> integer conversion always rounds to nearest.

• nicklas_a74

Points: 2