Display problem

Hi All
I have some real numnbers in my code
Ex:
1: 155.35254
2: 45:4353
how can I display to following result. I want to truncate some digit, I only need two digits after the point/
1:155.25
2:45.43
Thanks!

In reply to timag:
While printing the real number, use the format specifier as %0.2f instead of %f.

Exa:

$display("real num=%0.2f",num);

In reply to bdreku:

how about if i want to truncate some digit and then save to another real number?

In reply to timag:

Hello, just use the string methods atoreal. Here are the steps:

  1. Define a string, that you could eventually provide as input of an hypothetical function, which is going to represent the format. Let’s get up to the 3rd number after the binary point. Hence your string would be “0.2”.

  2. Use the $sformatf to get the final mentioned string, based on your previous example the expression would be: fstr=“%”,format,“f”; your_string_real=$sfomatf(fstr,real_number)

  3. After getting the string, use the real_truncated=your_string_real.atoreal().

4 now save the diff: diff = initial_number - real_truncated;

You can wrap up using a function or a macro is more up to you. This is the first approach coming up with I would go for so let me know if it works

In reply to timag:
If you want to truncate after some fixed number of fractional digits then you can multiply the number with “10^(num of fractional digits you want to keep)” and then can use int typecasting, $rtoi-$itor, $floor or $ceil and divide it with the same number.

Let’s say you want to truncate after 2 fractional digit,

module main;
  initial begin
    real num=12.3456;
    real a;
    $display("real num=%0.2f",num);

    // Way 1: Use typecast to int for rounding up and typecast back to real
    a = int'(num*10**2);
    a = real'(a)/10**2;  // a = 12.35
    $display("real a=%0f",a);

    // Way 2: Use $rtoi for rounding and $itor for converting back to real
    a = $rtoi(num*10**2);
    a = $itor(a)/10**2;  // a = 12.34
    $display("itor a=%0f",a);

    // Way 3: Use $floor for rounding down
    a = $floor(num*10**2)/10**2;  // a = 12.34
    $display("floor a=%0f",a);

    // Way 4: Use $ceil for rounding up
    a = $ceil(num*10**2)/10**2;  // a = 12.35
    $display("ceil a=%0f",a);
  end
endmodule