Continue to Site

# Rounding off values while dividing.

Status
Not open for further replies.

#### BojackHorseman

##### Newbie level 6
I have the code for dividing two numbers but whenever the final result is a decimal number, I always get the floor value. I want my output to be such that if the final value (lets say X) is greater than or equal to X.5 then the final value should be X+1 else remain X. Is there a way to do that with the following code ?

Code:
timescale 1ns / 1ps

module divide( input [31:0] in_and_2,
input [31:0] in_out_2,
output [31:0] rem,
output reg [31:0] quo

);
reg [31:0] a1;
reg [31:0] b1;
reg [31:0] p1;
integer i;

always @(in_and_2 or in_out_2) begin
a1 = in_and_2;
b1 = in_out_2;
p1 = 0;

for (i = 0; i < 32; i = i + 1) begin
p1 = {p1[30:0],a1[31]};
a1[31:1] = a1[30:0];
p1 = p1 - b1;

if (p1[31] == 1) begin
a1[0] = 0;
p1 = p1 + b1;
end

else
a1[0] = 1;
end
quo = a1;
rem = p1;

end

endmodule`

in_and_2 and out_and_2 are two numerical values which are obtained in the previous block.

what do you mean "when the final result is a decimal value"? You're dealing with binary numbers here, not decimal. What is your number format? Are these just integers? Fixed-point? two's complement?

And you do realize this is not synthesizable, right?

The short answer is you need to extend your data, add 0.5 (in whatever binary format you're using) to the result, and then truncate.

Status
Not open for further replies.