About the problem of sprintf intercepting decimals

WBOY
Release: 2016-10-23 00:12:48
Original
2325 people have browsed it

Question: Keep 1 decimal place, do not round, fill in 0 when it is an integer

Many people say to use sprintf('%.1f',$str);, but there are still problems with the results.
Finally, this method was used to solve the problem: echo sprintf('%.1f', floor( $str));

<code><?php
    $str1 = 12.34;
    $str2 = 12.35;
    $str3 = 12.36;
    echo sprintf('%.1f',$str1);//12.3
    echo sprintf('%.1f',$str2);//12.3
    echo sprintf('%.1f',$str3);//12.4
    
    echo sprintf('%.1f', floor($str3));//12.3
?>
</code>
Copy after login
Copy after login

Didn’t you say you don’t want to round? Why is it that when rounding, 5 is not included but 6 is included?
But other functions number_format($str) are all included at 5. Why is this?

Reply content:

Question: Keep 1 decimal place, do not round, fill in 0 when it is an integer

Many people say to use sprintf('%.1f',$str);, but there are still problems with the results.
Finally, this method was used to solve the problem: echo sprintf('%.1f', floor( $str));

<code><?php
    $str1 = 12.34;
    $str2 = 12.35;
    $str3 = 12.36;
    echo sprintf('%.1f',$str1);//12.3
    echo sprintf('%.1f',$str2);//12.3
    echo sprintf('%.1f',$str3);//12.4
    
    echo sprintf('%.1f', floor($str3));//12.3
?>
</code>
Copy after login
Copy after login

Didn’t you say you don’t want to round? Why is it that when rounding, 5 is not included but 6 is included?
But other functions number_format($str) are all included at 5. Why is this?

I tested it myself, and I guess it’s an issue with the accuracy of floating point number representation

<code class="php"><?php
    echo sprintf('%.0f', 12.5); //12
    echo sprintf('%.0f', 15.5); //16
?></code>
Copy after login

Reference

Whether Linux floating point numbers are rounded or rounded (depending on the representation of floating point numbers)

Related labels:
php
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