Search code examples
formattingtclsigned

Work arounds to printing negative zero in tcl


I'm dealing with rewriting a portion of a script to execute in a tcl because of a tool that's only available in tcl. In this code, the user can provide an option (-m for mirrored) to flip values around the y axis. (Basically, all the x values get multiplied by -1.) When printing out the values that resulted from this flipping, I realized that my output had a -0.0000 wherever the original script had 0.0000.

I fixed this issue by not multiplying the x value by -1 if it's equal to zero as bellow:

    if {$mirrored eq "t" && $text_x != 0} {
        #in tcl if you multiply 0 by -1 you get -0 we don't want that
        set text_x [expr {$text_x * -1.0}]
    }

I am okay with this solution, but it feels a bit weird to include this one case in my if statement. Is there a more concise, elegant or accepted way of doing this? Or any other way at all?


Solution

  • Add zero:

    Replicating your stated behaviour:

    % set x 0
    0
    % set y [expr {$x * -1.0}]
    -0.0
    

    and the remedy

    % set z [expr {$x * -1.0 + 0}]
    0.0