Home  >  Article  >  Backend Development  >  How to convert data to floating point number in php

How to convert data to floating point number in php

青灯夜游
青灯夜游Original
2022-04-27 15:43:224386browse

How to convert floating point numbers in php: 1. Use the floatval() function to get the floating point value of the variable, the syntax is "floatval (data to be converted)"; 2. Use the settype() function, the syntax is " settype(data to be converted, "float")" can convert the specified data to a floating point type.

How to convert data to floating point number in php

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

PHP provides two built-in functions, which can Convert other types of data to floating point numbers:

  • floatval() function

  • settype() function

1. Use the floatval() function

The floatval() function is a function that specifically converts other types into floating point types. It can obtain the floating point value of a variable.

Note: floatval cannot be used for arrays or objects.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$var = &#39;122.34343runoob&#39;;
echo "原数据类型:";
var_dump($var);
$float= floatval($var);
echo "修改后的类型:";
var_dump($float);
?>

How to convert data to floating point number in php

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$var = TRUE;
echo "原数据类型:";
var_dump($var);
$float= floatval($var);
echo "修改后的类型:";
var_dump($float);
?>

How to convert data to floating point number in php

2. Use the settype() function

settype( ) function can convert a value to a specified data type (controlled by the second parameter).

You only need to set the second parameter of the function to "float" to convert the data into a floating point number.

Note: This function will modify the original variable; if the setting is successful, it will return TRUE, if it fails, it will return FALSE.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$foo = "5bar"; // string
$bar = true;   // boolean
echo "原数据类型:";
var_dump($foo);
var_dump($bar);
settype($foo, "float");
settype($bar, "float");
echo "修改后的类型:";
var_dump($foo);
var_dump($bar);
?>

How to convert data to floating point number in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert data to floating point number in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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