-2

Possible Duplicate:
In PHP, how to print a number with 2 decimals, but only if there are decimals already?

Brothers I want to convert me any way I entered into a text field automatically turns 12 to 12.00

How possible work by php and javascript

Thanks

Community
  • 1
  • 1
  • 2
    possible duplicate of [In PHP, how to print a number with 2 decimals, but only if there are decimals already?](http://stackoverflow.com/questions/5648205/in-php-how-to-print-a-number-with-2-decimals-but-only-if-there-are-decimals-al) and/or [PHP: show a number to 2 decimal places](http://stackoverflow.com/questions/4483540/php-show-a-number-to-2-decimal-places) – mario Nov 06 '12 at 22:45

4 Answers4

2

In PHP its easy to do that by doing:

number_format($numberVar, 2);
topherg
  • 4,203
  • 4
  • 37
  • 72
1

Try this number_format() from PHP.net:

echo number_format(12, 2)
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
1

What, no javascript?

var x = 3;
alert(x.toFixed(2)); // 3.00

Will "work" for the case given, but so will:

alert(x + '.00');

There are bugs in toFixed in some older browsers with certain values so many write their own simple routine.

RobG
  • 142,382
  • 31
  • 172
  • 209
-2
$thisnum = $thisnum . ".00";

Proof of concept:

$thisnum = $thisnum . ".00";
echo ($thisnum + 4.55);

However, as pointed out by the community, this is something that will only work for the case mentioned in the question and will not handle any use cases that already have decimals. The other answers are better.

eric_spittle
  • 124
  • 3
  • 13
  • Good concept, but what if `$thisnum` is 12.00 or 12.00256? – Oliver Spryn Nov 06 '12 at 22:52
  • Then it isn't turning 12 into 12.00, which is what the question asked. I'll admit the other answers (which I didn't see until after I had posted) were better than mine, but I don't see getting -2 for answering the question that was asked. – eric_spittle Nov 06 '12 at 22:55
  • True, but this answer assumes only a specific case. When possible, don't reinvent the wheel, but also give answers which can apply to a variety of cases, not just the example that was used in this question. I retract my -1. – Oliver Spryn Nov 06 '12 at 22:57
  • Actually, unless you edit your answer, I can't retract my -1. – Oliver Spryn Nov 06 '12 at 22:58
  • Understood, my apologies, I do believe I should leave the answering to people much smarter than I. – eric_spittle Nov 06 '12 at 23:00