Matlab sprintf formatting

前端 未结 2 1315
既然无缘
既然无缘 2021-01-22 10:50

EDIT: I\'ve reworded the question to be clearer.

Does anyone know a clever way to get sprintf to print \"%.6f with trailing zeros elminated\"? This is

相关标签:
2条回答
  • 2021-01-22 11:05

    The problem is that you're mixing an int with a float in an array. Matlab doesn't like that so it will convert your int to a float so that all elements in the array are of the same type. Look at doc sprintf: you're now forced to use %f, %e or %g on floats

    Although I admit I like the STRREP method above (or below)

    0 讨论(0)
  • 2021-01-22 11:13

    EDIT: Updated to address the edited question...

    I don't think there's any way to do it with a particular format string for SPRINTF, but you could instead try this non-loop approach using the functions NUM2STR and REGEXPREP:

    >> mat = [12345678 123.45 123.456789012345];       %# Sample data
    >> str = num2str(mat,'<td>%.6f</td>');             %# Create the string
    >> str = regexprep(str,{'\.?0+<','\s'},{'<',''});  %# Remove trailing zeroes
                                                       %#   and whitespace
    >> fprintf(str);                                   %# Output the string
    
    <td>12345678</td><td>123.45</td><td>123.456789</td>  %# Output
    
    0 讨论(0)
提交回复
热议问题