![]() |
Strings in PHP can be converted to float very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert a string into a number in PHP, some of them are discussed below: Table of Content Using floatval() function.Note: The floatval() function can be used to convert the string into float values . Syntax: $floatvar = floatval($stringvar) Return Value: This function returns a float. This float is generated by typecasting the value of the variable passed to it as a parameter. Example:
Output: Converted float = 1000.314 Using TypecastingNote: Typecasting is the explicit conversion of data type because the user explicitly defines the data type in which he wants to cast. We convert String into Float. Syntax: $floatvar = (float)$stringvar Example:
Output: Converted float = 1000.314 Using number_format() functionNote: The number_format() function is an inbuilt function in PHP that is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure. Syntax: string number_format( $number, $decimals, $decimalpoint, $sep ) Return Value: It returns a formatted number in case of success, otherwise it gives E_WARNING if it fails. Example:
Output: Converted float = 1000.314564 Using sscanf() FunctionAnother approach to convert a string into a float is by using the sscanf() function. This function parses input from a string according to a specified format. Syntax:sscanf($string, $format, &$variable); Example:
Output Converted float = 1000.314 |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 8 |