In this tutorial we will show you the solution of PHP convert string to float with 2 decimal, it is very easy to convert string to float in php.
And also there are many methods with help of which we can convert a string into number using php. Let discuss some of them below.
Step By Step Guide On PHP Convert String To Float With 2 Decimal :-
Here, the methods which are used to convert string to float are
- Using floatval() function
- Using number_format() function
- And using typecasting
Now, let us discuss them one by one. In this article we are going to understand the most prefer method that is number_format() method.
In next articles, we will understand about other two methods. The codes given below help you to understand number_format().
<!DOCTYPE html> <html> <head> <title> php two decimal places without rounding </title> </head> <body> <?php // Number in string format $var = "1284.50"; // converts string into float with 2 decimals $number = number_format($var, 2); // result echo "resulted float = ".$number; ?> </body> </html>
- First, we write <! DOCTYPE html> which we used as an instruction to the web browser about what version of HTML file is written in.
- Secondly, the <html> tag is used to indicate the beginning of an HTML document.
- As above now <head> tag is used to contain information about web page. In this tag a <title> tag is used which helps us to specify a webpage title. Both <head> and <title> tags are Paired tags. So, both have </head> and </title> ending tags respectively.
- Here, then we create a body tag. All the content which we want to show on browser’s screen or display is always written inside this codes.
- Here, today we are going to use the easiest and most preferred method. In this article, as we already say that we are going to use number_format() function.
- To done this article, first we create a basic structure of php and inside them we write our php code.
- As you see, we assigns a string to variable that is var. We can also get number from user dynamically and assigns it to some variable.
- Now, after that we use the required number_format() function on that variable $var in which we store our string and the decimal required given value is 2. It means that there must be two decimals to output.
- Now, after this we have to print the output. We can echo the number directly using echo before function. And another way is to store the number inside a variable and use that variable to display using echo.
- At last, the <body> and <html> tags are closed with </body> and </html> respectively.
Conclusion :-
At last in conclusion, here we can say that with the help of this article we are able to understand how to convert string to float with 2 decimal in php.
I hope this tutorial on PHP convert string to float with 2 decimal helps you and the steps and method mentioned above are easy to follow and implement.