php

Reverse sign of number stored as string


This is a trivial operation but it has revealed some tricky points. I have a string in PHP, say '234.00'. I want to convert that to a negative number, and preferably get a string in the end. So the test cases should be

'234.00'  ==> '-234.00'
'-234.00' ==> '234.00'
'0.00'    ==> '0.00'

The original code was

$signReversed = $stringNumber * -1.0

but that has problems because I really need a string for consistency with other code. So I tried

$signReversed = strval($stringNumber * -1.0)

but this fails on the last test case, because I get '-0' -- negative zero as a string.

Suggestions on the best way to do this?


Solution

  • What about this

    should work for small numbers, large numbers and strings can contain NULL bytes

    function flipSign($stringNummer) {
       if ((string)$stringNummer !== $stringNummer) // fast !is_string check
          throw new Exception('input should be a string');
       return number_format($stringNummer * -1, 2, '.', '');
    }
    
    /**
     * NULL byte test 
     */
    var_dump(flipSign("00\0.10"));   // string(5) "-0.10" 
    var_dump(flipSign("-00\0.10"));  // string(4) "0.10"
    
    var_dump(flipSign("00.10"));   // string(5) "-0.10" 
    var_dump(flipSign("-00.10"));  // string(4) "0.10"
    
    var_dump(flipSign("234.00"));   // string(7) "-234.00 
    var_dump(flipSign("-234.00"));  // string(6) "234.00"
    
    var_dump(flipSign("234.20"));   // string(7) "-234.20"
    var_dump(flipSign("-234.20"));  // string(6) "234.20" 
    
    var_dump(flipSign("100000.20"));   // string(10) "-100000.20"
    var_dump(flipSign("-100000.20"));  // string(9)  "100000.20"