5

What is the best way to round a real type in systemVerilog according:

Case positive: if fraction >= 0.5 ---> round return the "integer part" + 1 (for example 4.5 --->5) if fraction < 0.5 ---> round return the "integer part" (for example 4.2 --->4)

Case negative: if fraction >= 0.5 ---> round return the "integer part" -1 (for example -4.5 --->-5) if fraction < 0.5 ---> round return the "integer part" (for example -4.2 ---> -4)

sara8d
  • 403
  • 4
  • 17
  • 32

1 Answers1

5

Rounding reals to integers is well described in the IEEE Std 1800-2012 LRM.

IEEE Std 1800-2012 § 6.12.2 Conversion

Real numbers shall be converted to integers by rounding the real number to the nearest integer, rather than by truncating it. Implicit conversion shall take place when a real number is assigned to an integer. If the fractional part of the real number is exactly 0.5, it shall be rounded away from zero.

IEEE Std 1800-2012 § 20.5 Conversion functions

$rtoi converts real values to an integer type by truncating the real value (for example,123.45 becomes 123). $rtoi differs from casting a real value to an integer or other integral type in that casting will perform rounding instead of truncation. Directly assigning a real value to an integral type will also round instead of truncate.

According to the LRM, int_val = 4.5 or int_val = int'(4.5) will both become 5. And int_val = -4.5 or int_val = int'(-4.5)will both become -5.

Direct assignment verses casting may have different performance depending on the simulator. I'd assume casing is perfected since it is more explicit for anyone reviewing the code and the simulator. Plus casting gets gives more control on the bit width.

Greg
  • 18,111
  • 5
  • 46
  • 68