In PHP (using built-in functions) I'd like to convert/format a number with decimal, so that only the non-zero decimals show. However, another requirement of mine is that if it's a number without a decimal value, I'd still like to show that zero. Examples:
9.000 -> 9.0
9.100 -> 9.1
9.120 -> 9.12
9.123 -> 9.123
rtrim($value, "0")
almost works. The problem with rtrim is that it leaves 9.000
as 9.
. sprintf()
seemed like a candidate, but I couldn't get it to have a variable amount of decimals. number_format()
serves a different purpose, and those were all I could come up with...
Again, I'd like to point out that I am not looking for your homemade solutions to this, I'm looking for a way to accomplish this using internal PHP functionality. I can write a function that will accomplish this easily myself, so hold answers like that.
Out of the box that isn't possible because you have two different ways of treating the fragment of your floats. You'll first have to determine how many non-zero numbers there are in your fragment and then act accordingly with sprintf.
Assuming the number is encoded as or cast to a string, here's a general purpose approach:
try something like this
will display "2"
If you want a built-in solution and you're using a PHP version later than 4.2 you could try
floatval()
:prints
but
prints
Hope this helps.
Shouldn't it be?:
The PHP preg_replace syntax is
Output: