Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative value format with in parentheses

Tags:

php

normally php will output negative integer with this format -1234, how to it show in parentheses format (1234)

example:

$foo = 10 - 20;
// output: $foo = -10
// expected output $foo = (10)
like image 520
GusDeCooL Avatar asked Oct 24 '25 01:10

GusDeCooL


2 Answers

I don't think there is a way to make PHP do this automatically.

echo ($foo < 0 ? "(".abs($foo).")" : $foo);

is the shortest solution that comes to mind.

like image 99
Pekka Avatar answered Oct 25 '25 13:10

Pekka


In my opinion the easiest way is creating your own print function, out of the box with php this isn't possible.

function print_val($int){
    return ($int < 0) sprintf('(%d)', abs($int)) : $int;
}
like image 32
ChrisR Avatar answered Oct 25 '25 13:10

ChrisR