0

My number is 495 plain and simple.

I'm trying to format this number to have it display $4.95

what I've done is number_format($number, 2, '.', '')

but that outputs 495.00

I know it can't be this difficult. Anyone familiar with number_format?

I just need it to add a decimal two numbers from the right so the cents are always displayed. ex. 4.95, 12.58, 23.39... You get the idea.

Thank you.

2
  • Whoops, my bad. Read the question wrong, if I could delete this I would! Commented Oct 29, 2014 at 21:57
  • Also, you should note the last two parameters in that instance are cruft (those are the defaults) Commented Oct 29, 2014 at 21:58

3 Answers 3

2

If you're working with integers instead of floats, you'd first have to divide by 100.

$number = 495;
echo number_format($number/100, 2, '.', '')
Sign up to request clarification or add additional context in comments.

2 Comments

Oh my gosh! I can't believe it. My brain is done today. Thanks jboneca
@ValleyDigital sure thing, bud!
0

Assuming your numbers are all whole numbers you can do the following:

$mynum = 495;

function formatMyNum($num) {
    return $num/100;
}

2 Comments

Why writing function for everything when you just can divide $number by 100?
I assume you would want to reuse the logic. Personal preference I guess. A developer coming after you many not know why you are dividing by 100 so a function can be self documentation
0

Number format just displays floats using N number of decimals and the decimal/thousand separator characters you choose.

If you passed 4.95 to it, it would show fine so to do that just divide your $number by 100 before passing it to the function.

echo number_format($number/100, 2, '.', '');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.