PHP十进制计算 [英] PHP Decimal calculations

查看:142
本文介绍了PHP十进制计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到你必须小心使用PHP进行浮点比较和计算。我不是PHP专家,所以我想问问社区什么是在PHP中进行精确的小数计算的最佳方法。



我正在开发一个计时卡应用程序在哪里计算每周输入的所有时间。超过40小时的任何事情都被视为加班。然后,我想根据进入总时间的百分比,将这个加班时间分配给每个时间条目。



示例:

星期一= 10小时

总时间= 50小时

加班时间= 10小时

总时间百分比(0.2)=星期一(10小时)/总时间(50小时)

加班时间分配到星期一(2小时)=总加班时间(10小时)*总时间百分比(0.2)









$ b $ $ p $ b星期一(8小时)=星期一 - 加班时间分配到星期一(2小时)

星期一加班= 2小时



使用整数作为原始条目似乎并不糟糕,但是当我开始使用浮点数并每天有多个时间条目时会发生什么?每次输入将会有一部分时间分配给它,但是我需要确保不要再分配更多的加班时间,然后我也需要确保每天和整个计时卡的总时间与原来的一样进入。我读过比较浮动php是不安全的。我该如何计算呢?此外,最后输入的数字必须舍入到2个小数点(。##)。

解决方案

阅读浮点指南了解为什么您必须小心混合浮点数和小数点的概念(这与PHP完全无关)。



它也有一个用于PHP的作弊表


I was reading that you have to be careful with floating point comparisons and calculations in PHP. I'm not an expert at PHP so I thought I would ask the community what is the best way to do accurate decimal calculations in PHP.

I'm developing a timecard application where it calculates all the time entered for the week. Anything over 40 hours is considered overtime. I then want to distribute that overtime back across each time entry based on the percentage that entry is of the total time.

Example:

Monday = 10 hours
Total Time = 50 hours
Total Overtime = 10 hours

Percent of Total time (0.2) = Monday (10 hours) / Total Time (50 hours)
Overtime to Allocate to Monday (2 hours) = Total Overtime (10 hours) * Percent of Total Time (0.2)

Now make a new entry for Monday with 2 hours of overtime and subtract 2 hours from original entry.

New Entries:
Monday (8 hours) = Monday - Overtime to Allocate to Monday (2 hours)
Monday Overtime = 2 hours

Things don't seem to bad when using integers as your original entries but what will happen when I start using floats and have multiple time entries per day? Each time entry will have part of the total overtime allocated to it but I need to make sure not to allocate more overtime then is available and I also need to make sure the total time for each day and for the whole timecard is the same as originally entered. I read comparing floats in php are not safe. How should I do the calculation. Also, the final entered numbers have to be rounded to 2 decimal points (.##)

解决方案

Read The Floating-Point Guide to understand why exactly you have to be careful with mixing floating-point numbers and the concept of "decimals" (which has absolutely nothing to do with PHP specifically).

It also has a cheat-sheet for PHP.

这篇关于PHP十进制计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆