system-verilog

Align negative and positive numbers real numbers using format string in SystemVerilog


Here is the function that converts a block of 8x8 numbers into a string matrix:

 function string float_block_to_string(input float_8x8_block_t float_block);

    string str;
    string fmt;
    real   value;

    str = "";
    // Loop over the array and write 8 values per line
    for (int j=0; j<8; j++) begin
      if (j==0)
        str = "{\n";
      for (int i=0; i<8; i++) begin
        value = float_block[j*8+i];
        str = {str, $sformatf("%8.4f  ", value)};
      end
      if (j<7) begin
        str = {str, "\n"};
      end
      if (j==7) begin
        str = {str, " }; "};
     // str = {str.substr(0, str.len()-3), " }; "};
      end
    end
    return str;
  endfunction

Here is the output:

{
-43.4064  424.5029    0.0000  -149.0656   -0.0000   99.6025    0.0000  -84.4389  
112.6610  383.1046    0.0000  -134.5284   -0.0000   89.8890   -0.0000  -76.2042  
  0.0000    0.0000    0.0000   -0.0000   -0.0000   -0.0000    0.0000    0.0000  
-39.5613  -134.5284   -0.0000   47.2401    0.0000  -31.5648    0.0000   26.7594  
 -0.0000   -0.0000   -0.0000    0.0000    0.0000   -0.0000   -0.0000    0.0000  
 26.4340   89.8890    0.0000  -31.5648   -0.0000   21.0909    0.0000  -17.8800  
  0.0000   -0.0000    0.0000    0.0000    0.0000   -0.0000    0.0000    0.0000  
-22.4097  -76.2042   -0.0000   26.7594    0.0000  -17.8800   -0.0000   15.1580   }; FDCT_Cr     0V,    0H;  10,    0,    0, l=1

The text is not aligned. This is inspite of the use of the format string. The minus symbol for the negative numbers is the primary issue. What is the correct way to fix this?


Solution

  • %w.df

    The w number that appears after the % symbol is the minumum width of the formatted corresponding argument. That number includes space for the sign and decimal point. The d number after the decimal point is the precision modifier. Your w needs to be at least 9 for the values you want to show.

    This is the same behavior as in C printf().