Home > Backend Development > PHP Tutorial > PHP method to format MYSQL to return float type_php tips

PHP method to format MYSQL to return float type_php tips

WBOY
Release: 2016-05-16 19:55:03
Original
1657 people have browsed it

The example in this article describes how PHP formats MYSQL to return float type. Share it with everyone for your reference, the details are as follows:

Get the float field of mysql in PHP. After echo output, the decimal part contains multiple 0.

You can use floatval($num) to round off 0.

If you want to retain decimal places, you can use number_format($num, 2);

The number_format function rounds values ​​that exceed the specified number of digits.

If you don’t want to round, keep all decimals. You can use the following methods:

// 如仅想保留两位小数可用 number_format($num, 2);
echo f('1001.334534', 2) . '<br>'; // 1001.334534
echo f('-1001.000', 2) . '<br>'; // -1001.00
echo f('1001.3', 5) . '<br>'; // 1001.30000
echo f('1001.33') . '<br>'; // 1001.33
echo f('1001.000') . '<br>'; // 1001
// 格式化小数,但不四舍五入,如有小数则全保留,无小数则添加0;
function f($num, $v = 0)
{
  $num = floatval($num);
  if ($v > 0)
  {
    $num = '' . $num;
    $arr = explode('.', $num);
    if (count($arr) === 1)
    {
      $num .= '.' . str_repeat('0', $v);
    }
    else
    {
      $v -= strlen($arr[1]);
      if ($v > 0)
        $num .= str_repeat('0', $v);
    }
  }
  return $num;
}

Copy after login

Readers who are interested in more PHP-related content can check out the special topics on this site: "Summary of PHP network programming skills", "Introduction to PHP basic syntax tutorial", "Summary of PHP operating office document skills (including word, excel, access, ppt)", "Summary of PHP date and time usage", "PHP object-oriented programming introductory tutorial》, "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone in PHP programming.

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