1

Have a text box which get data for price. If someone enter something like "3." i want to get it converted to "3.0" i cannot append "0" simply in the end because then if it is "100" gets converted to "1000"

Also is_numeric("3.") returns 1.

Whats the possible way round?

2
  • search for a decimal point being the last character in a the string, if it is, add a zero after? Commented Jul 5, 2012 at 10:27
  • did that, was searching is there is a function to do that other way Commented Jul 5, 2012 at 10:51

3 Answers 3

3

You need number_format():

number_format('3', 1, '.', ''); // = 3.0
number_format('3.', 1, '.', ''); // = 3.0
number_format('3.22', 1, '.', ''); // = 3.2
number_format('3.22abc', 1, '.', ''); // = 3.2 and a "PHP Notice:  A non well formed numeric value encountered"
number_format('abc3.22', 1, '.', ''); // = "PHP Warning:  number_format() expects parameter 1 to be double, string given"
Sign up to request clarification or add additional context in comments.

3 Comments

what if my number is in string format? floatval is not converting it. Any idea?
I've echoed the result and it is 3.0... floatval will stop conversion on first non-number symbol, so "3", "3.", "3.1234567" will work. "3.123456abc" will give you a notice. "abc123" will give you a warning.
@amitchhajer - cast the number to a float first? Such as: number_format((float) '3.22', 1, '.', ''); The only drawback to this approach is that number_format returns a string and not a float or int.
0

Try casting it as a float first, and then using number_format to format it.

$number = (float) $_POST['text_box'];
number_format($number, 1, '.', '');

Hope this helps

Comments

0

You will need to use number_format() for this.

number_format($number, 1, ".", ""); will do the trick for you:

  • 3 becomes 3.0
  • 2500 becomes 2500.0

4 Comments

Yeah, it looks the the OP wants valid numbers, so change the fourth parameter from " " to ''.
@RogueCoder Eh... it was an oversight. Thanks for the notice, I've edited the answer.
You actually need to add the '' as the fourth parameter since it defaults to ','.
@RogueCoder I didn't know that. Apparently, on my system it defaults to ''. Might be locale differencies.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.