Home > Backend Development > PHP Problem > How to cast value to float in php

How to cast value to float in php

青灯夜游
Release: 2023-03-13 08:44:02
Original
3654 people have browsed it

Method: 1. Add the target type "(float)" enclosed in parentheses before the variable, the syntax is "(float)$val"; 2. Use floatval(), the syntax "floatval($val )"; 3. Use settype(), the syntax is "settype($val, "float")".

How to cast value to float in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php forces the value Type conversion to float

Method 1: Add the target type enclosed in parentheses "(float)"## before the variable to be converted #

<?php
header("Content-type:text/html;charset=utf-8");
$str = &#39;123.456abc&#39;;
$float = (float)$str;
echo $float."<br>";
echo &#39;变量 $float 的类型为:&#39; . gettype($float) . &#39;<br>&#39;;
?>
Copy after login

How to cast value to float in php

Method 2: Use floatval() function

floatval(): used to obtain the floating point value of a variable;

<?php
header("Content-type:text/html;charset=utf-8");
$str = &#39;123.456abc&#39;;
$float = floatval($str);
echo $float."<br>";
echo &#39;变量 $float 的类型为:&#39; . gettype($float) . &#39;<br>&#39;;
?>
Copy after login

Output result:

How to cast value to float in php

Method 3: Use settype() function

Syntax:

The

settype ( $var ,$type )
Copy after login

settype() function is used to set the variable $var to the specified $type type.

Example

<?php
header("Content-type:text/html;charset=utf-8");
$str = &#39;123.456abc&#39;;
settype($str,"float");
echo $str."<br>";
echo &#39;修改后的类型为:&#39; . gettype($str) . &#39;<br>&#39;;
?>
Copy after login

Output result:

How to cast value to float in php

Description: The settable value of $type

  • "boolean" (or "bool" since PHP 4.2.0)

  • "integer" (or "int" since PHP 4.2.0)

  • "float" (only available after PHP 4.2.0, "double" used in older versions is now disabled)

  • "string"

  • "array"

  • "object"

  • "null" (from PHP 4.2.0 onwards)

settype() function changes the type of the variable itself.

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to cast value to float in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template