# Formatting a number

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hello

I am looking if there is a better way to write the following if possible.

I would like to display the negative sign in front of the dollar sign
when the unit is negative.

if(\$units < 0){
\$f_units = '-\$' . number_format(\$units * -1);
} else {
\$f_units = '\$' . number_format(\$units);
}

I need \$units to stay untouched since I am using it in a calculation
later down.

Thanks
Scotty

## Re: Formatting a number

How do you define "better". I can give you "other" ways to do it, but
I have no idea what your criteria would be in deciding whether any of
them are better.

Here's one:
\$f_units = ((\$units<0)?'-':'').number_format(abs(\$units));

## Re: Formatting a number

On 1/29/2013 2:19 AM, Captain Paralytic wrote:

I originally wrote 'elegant' but I think you got the jest.

I like one liners as yours and forgot about the abs() function
Thanks.

## Re: Formatting a number

On Tue, 29 Jan 2013 02:19:14 -0800 (PST), Captain Paralytic

I think you mean:=20
\$f_units = ((\$units<0)?'-\$':'\$').number_format(abs(\$units));

## Re: Formatting a number

Or I may have meant:
\$f_units = ((\$units<0)?'-':'').'\$'.number_format(abs(\$units));

## Re: Formatting a number

On Wed, 30 Jan 2013 02:05:01 -0800 (PST), Captain Paralytic

Yes, I thought of that one and wondered if there is any difference in
their efficiency, however small. I went with the first only because it
was fewer characters.=20

## Re: Formatting a number

On 1/30/2013 2:05 AM, Captain Paralytic wrote:

Yes I like this one, tks. @cp

## Re: Formatting a number

On 29/01/13 04:45, Scott Johnson wrote:

try printf or sprintf..

--
Ineptocracy

(in-ep-toc’-ra-cy) – a system of government where the least capable to
lead are elected by the least capable of producing, and where the
members of society least likely to sustain themselves or succeed, are
rewarded with goods and services paid for by the confiscated wealth of a
diminishing number of producers.

## Re: Formatting a number

wrote:

Have you looked at money_format()
Might be available on all systems though.

--
Regards, Paul Herber, Sandrila Ltd.