How to ensure that each part is equal to 1 when calculating the percentage in PHP?

Source: Internet
Author: User
In PHP, how do I ensure the sum of parts is 1? This post was last edited by Jasmine_xiaocao from 2013-05-1809: 51: 53 $ total $ a + $ B + $ c + $ d; $ percentA ceil ($ a * 100.0 $ total); $ How do I ensure the sum of each department and 1 when calculating the percentage in percentB cei PHP?

This post was last edited by Jasmine_xiaocao at 09:51:53

$total = $a+$b+$c+$d;$percentA = ceil($a*100.0/$total);$percentB = ceil($b*100.0/$total);$percentC = ceil($c*100.0/$total);$percentD = ceil($d*100.0/$total);

The above code does not seem to ensure that the final sum is 100%

$percentD = 100-$percentA-$percentB-$percentC;

Is there any other method besides this?

------ Solution --------------------

$a = array(1,2,3,3);$total = array_sum($a);array_walk($a, function(&$item, $key, $prefix) { $item = round($item*100/$prefix); }, $total);if($d = (100 - array_sum($a))) $a[rand(0, count($a)-1)] += $d;print_r($a);

The above is how to ensure the sum of parts and values of 1 when calculating the percentage in PHP. For more information, see PHP Chinese network (www.php1.cn )!

Related articles:

Php code for displaying the slice percentage

How to calculate the percentage of the progress bar displayed at the end of the vote?

PHP execution progress percentage code

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.