danack/float-hex
Composer 安装命令:
composer require danack/float-hex
包简介
Float to hex strings, and float comparison.
README 文档
README
Functions for converting float to a hex-string and back again, and also for showing two floating point numbers as a binary representation.
Example
<?php require __DIR__ . "/vendor/autoload.php"; use function FloatHex\floathex; use function FloatHex\floathex32; use function FloatHex\float_compare; $value = 1.2345; echo floathex($value) . "\n"; // Output: 3ff3c083126e978d echo floathex32($value) . "\n"; // Output: 3f9e0419 echo float_compare(1.2345, 1.234500000001); // Output: // ┌──────┬─────────────┬──────────────────────────────────────────────────────┐ // │ Sign │ Exponent │ Mantissa │ // │ 0 │ 01111111111 │ 0011110000001000001100010010011011101001011110001101 │ // │ 0 │ 01111111111 │ 0011110000001000001100010010011011101010100100100101 │ // │ - │ ----------- │ --------------------------------------xxxxx-x-x-x--- │ // └──────┴─────────────┴──────────────────────────────────────────────────────┘
Why?
Some of the tests in Imagick compare floats, and trying to figure out if the float is off by a rounding error, or by a larger amount was annoying.
Comparing the bits makes it easier to see what is going on visually. e.g. for comparing 0.3 with 0.1 + 0.2:
<?php echo float_compare(0.3, 0.1 + 0.2);
The output is:
┌──────┬─────────────┬──────────────────────────────────────────────────────┐
│ Sign │ Exponent │ Mantissa │
│ 0 │ 01111111101 │ 0011001100110011001100110011001100110011001100110011 │
│ 0 │ 01111111101 │ 0011001100110011001100110011001100110011001100110100 │
│ - │ ----------- │ -------------------------------------------------xxx │
└──────┴─────────────┴──────────────────────────────────────────────────────┘
Straight away, you can see that the difference between the numbers is in the lowest bit.
hexfloat and floathex32 might be useful for people who need to transfer floats precisely over text channels.
Exact float value
If you want to see the exact value that a float is stored as, this can be done with number_format.
echo number_format(1.22, 64);
// Output is:
// 1.2199999999999999733546474089962430298328399658203125000000000000
TODO
- Check behaviour around NANs and INFs
- Error detection on bad input strings.
danack/float-hex 适用场景与选型建议
danack/float-hex 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 876 次下载、GitHub Stars 达 11, 最近一次更新时间为 2020 年 09 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 danack/float-hex 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 danack/float-hex 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 876
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 11
- 点击次数: 7
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2020-09-12