Shortreal datatype not driving exact value

In reply to Reuben:

Hi Reuben,

I’m not sure why you’re getting a different value (probably would need to see the code to figure that out), but I might be able to help you with the rounding. There’s no rounding function in SV/Verilog, but reals are rounded if you convert them to integers. You could also use $shortrealtobits(), modify the bits, and then $bitstoshortreal() to convert it back again. Or you could call a C function to round through the DPI.

But probably the easiest way to round a shortreal would be to use the $swrite() function to convert it to a rounded string and then convert it back to a shortreal:

module shortreal_round();

shortreal myreal = 3.1415926535897932384626433832795028841971693993751058209749445923078;
shortreal rounded;
string str;

initial begin
  $swrite(str, "%0.4f", myreal);
  rounded = str.atoreal();

  $display("rounded number = %f", rounded);
end


endmodule

The output of this simulation using Questasim is:

# rounded number = 3.141600

Notice the fourth digit gets rounded. Just change the format specifier in the $swrite to “%0.2f” and you can round it to two digits.
Good luck,
-Doug