PHP floating-point numbers display and turn into strings

Source: Internet
Author: User
Tags printf

You might think it's easy to turn floating point (float) into a string in PHP, but the usual approach hides serious bugs. Because PHP has a very unreasonable way of handling floating-point numbers, there is a loss of precision. After research, in fact, PHP in the display of floating point of the problem, can also be said to be a bug. PHP built-in Echo, Var_dump, Json_encode, string concatenation functions (instructions) in the display floating-point numbers are problematic, resulting in loss of precision.

<?php

$a = 1315537636.338467;

printf ("%f", $a); echo "\ n";

echo $a. "\ n";

echo $a; echo "\ n";

?>

Results

1315537636.338467

1315537636.3385

1315537636.3385

In other words, the most convenient way to use PHP to convert floating-point numbers to strings or display is not possible, you must use printf/sprintf to convert floating-point numbers to strings.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.