Home  >  Article  >  Backend Development  >  How to convert float to string in php

How to convert float to string in php

青灯夜游
青灯夜游Original
2021-09-09 12:14:193696browse

php method to convert float to string: 1. Add the target type "(string)" enclosed in parentheses before the float variable to be converted; 2. Use "strval($float)" statement; 3. Use the "settype($float,"string")" statement.

How to convert float to string in php

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

Method 1: In the computer to be converted The float variable is preceded by the target type (string) enclosed in parentheses

<?php
$float=3.14;
$str=(string)$float;
var_dump($str);
?>

Output result:

How to convert float to string in php

Method 2: Use the strval() function

strval() function to get the string value of the variable

<?php
$float=125.254;
$str=strval($float);
var_dump($str);
?>

Output result:

How to convert float to string in php

Method 3: Use the settype() function

settype ($var,$type)The function is used to set or convert the type of a variable, and $var is converted to $type type. Possible values ​​for

type are:

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

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

  • "float" (only available after PHP 4.2.0, for older versions The "double" used is now deprecated)

  • "string"

  • "array"

  • "object"

  • "null" (from PHP 4.2.0 onwards)

Example:

<?php
$float=54.254;
$str=settype($float,"string");;
var_dump($float);
?>

Output result:

How to convert float to string in php

Description: settype() will modify the type of the variable itself. If the setting is successful, it will return true, and if it fails, it will return false.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert float to string 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