Download the PHP package gryfoss/int-precision-helper without Composer
On this page you can find all versions of the php package gryfoss/int-precision-helper. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download gryfoss/int-precision-helper
More information about gryfoss/int-precision-helper
Files in gryfoss/int-precision-helper
Package int-precision-helper
Short Description Helper class for handling decimal precision by storing floats as integers to avoid floating-point precision issues in database storage and calculations.
License MIT
Informations about the package int-precision-helper
IntPrecisionHelper
A robust PHP library for handling decimal precision by storing floating-point numbers as integers, designed to eliminate floating-point precision issues in database storage and financial calculations.
Installation
Purpose
This library solves common floating-point precision issues by storing decimal numbers as integers. For example:
12.34is stored as1234(multiplied by 100)- All calculations are performed on integers to maintain precision
- Results are converted back to decimal representation when needed
This approach is particularly useful for:
- Financial calculations - Ensuring precise monetary computations
- Percentage calculations - Accurate rate and ratio calculations
- Database storage - Consistent decimal representation across systems
- Scientific calculations - Where precision is critical
Why PHP 8.4+ is Required
This library requires PHP 8.4 or higher because it utilizes PHP's native bcround() function, which was introduced in PHP 8.4. The bcround() function provides:
- High-precision rounding for decimal calculations
- Consistent behavior across different platforms
- Performance optimization over custom rounding implementations
- BCMath integration for seamless mathematical operations
Core Functionality
Input Conversion Methods
fromString(string $value, bool $lessPrecise = false): int
Converts a string representation of a decimal number to a normalized integer.
Parameters:
$value- String representation of a decimal number (e.g., "12.34", "0.05")$lessPrecise- Optional performance mode for large numbers
Example:
Validation: Throws InvalidArgumentException for invalid input formats.
fromFloat(float $value, bool $lessPrecise = false): int
Converts a float to a normalized integer representation.
Parameters:
$value- Float value to convert$lessPrecise- Optional performance mode
Example:
normalize(mixed $value, bool $lessPrecise = false): int
Universal conversion method that automatically detects input type and converts to normalized integer.
Parameters:
$value- Value to normalize (float, string, or integer)$lessPrecise- Optional performance mode for large numbers
Examples:
Error Handling: Throws InvalidArgumentException for unsupported types (arrays, objects, etc.) or invalid string formats.
Output Conversion Methods
denormalize(int $normalizedValue): float
Converts a normalized integer back to its decimal representation as a float.
Parameters:
$normalizedValue- Normalized integer value
Example:
toView(int $value, int $decimalPlaces = 2): string
Converts a normalized integer back to a human-readable string representation.
Parameters:
$value- Normalized integer valuedecimalPlaces- Number of decimal places to display (default: 2)
Example:
toFloat(int $value): float
Converts a normalized integer back to a float representation.
Example:
Mathematical Operations
normMul(int ...$numbers): int
Performs multiplication on normalized integers while maintaining precision.
Example:
Protection: Throws OverflowException if result would exceed PHP_INT_MAX.
normDiv(int $dividend, int $divisor): int
Performs division on normalized integers with precision preservation.
Example:
Protection: Throws DivisionByZeroError if divisor is zero.
normAdd(int ...$numbers): int
Adds multiple normalized integers.
Example:
normSub(int $minuend, int $subtrahend): int
Subtracts two normalized integers.
Example:
Utility Methods
calculatePercentage(int $value, int $total): ?int
Calculates percentage as a normalized integer.
Example:
normCompare(int $a, int $b): int
Compares two normalized integers.
Returns:
-1if$a < $b0if$a == $b1if$a > $b
Example:
isValid(mixed $value): bool
Validates if a value is a valid normalized integer.
Example:
Usage Examples
Basic Conversions
Round-Trip Conversions
Mathematical Operations
Quick Reference
New Universal Methods (Recommended)
normalize(mixed $value, bool $lessPrecise = false): int
One method to convert any supported type to normalized integer:
- ✅ Floats:
normalize(12.34)→1234 - ✅ Strings:
normalize("12.34")→1234 - ✅ Integers:
normalize(12)→1200 - ❌ Arrays/Objects: Throws
InvalidArgumentException
denormalize(int $normalizedValue): float
Convert normalized integer back to decimal float:
denormalize(1234)→12.34denormalize(99)→0.99
Type-Specific Methods (Legacy)
| Input Type | Method | Example |
|---|---|---|
| String | fromString("12.34") |
1234 |
| Float | fromFloat(12.34) |
1234 |
| Integer | $value * 100 |
Manual |
| Output Type | Method | Example |
|---|---|---|
| String | toView(1234) |
"12.34" |
| Float | toFloat(1234) or denormalize(1234) |
12.34 |
When to Use Each Method
- 🎯 Use
normalize()when input type varies or unknown - ⚡ Use
fromString()/fromFloat()for known types (slight performance benefit) - 📊 Use
denormalize()for float output - 📝 Use
toView()for formatted string display
Advanced Features & Error Handling
Input Validation
The library provides comprehensive input validation with descriptive error messages:
Division by Zero Protection
All division operations are protected against division by zero:
Overflow Protection
The library detects and prevents integer overflow conditions:
Performance Modes
For performance-critical applications with very large numbers:
Breaking Changes from Original
⚠️ Important: The legacy NormMul and NormDiv methods have been removed due to PHP's case-insensitive function names conflicting with the new normMul and normDiv methods.
Migration Guide:
NormMul()→normMul()NormDiv()→normDiv()calculatePercentage()now returnsint|nullinstead offloat|null
Configuration & Customization
Custom Precision Factor
You can customize the precision factor by extending the class:
Available Constants
PRECISION_FACTOR- Multiplier for decimal conversion (default: 100)DECIMAL_PLACES- Default decimal places for output (default: 2)
Requirements
- PHP 8.4+ - Required for native
bcround()function support - BCMath extension - Essential for high-precision mathematical operations
- 64-bit system - Recommended for handling larger integer values
Testing & Quality Assurance
This library maintains 100% code coverage and follows rigorous testing standards to ensure reliability and precision.
Test Coverage Statistics
- 📊 100% Code Coverage - Complete line coverage with comprehensive testing
- 🧪 74 Test Cases - Comprehensive unit test suite
- ✅ 151 Assertions - Detailed validation of all functionality
- 🎯 556 Feature Scenarios - Behavior-driven development tests
- 🚀 Edge Case Coverage - All error conditions and boundary cases tested
- � Continuous Integration - Automated testing on every commit
Running Tests Locally
Unit Tests with Coverage
Feature Tests (Behavioral Testing)
Quick Test Coverage Check
Test Categories
Unit Tests (tests/IntPrecisionHelperTest.php)
- ✅ Conversion Methods - String/float to integer and back
- ✅ Universal Normalize/Denormalize - Type-agnostic conversion methods
- ✅ Mathematical Operations - Multiplication, division, addition, subtraction
- ✅ Error Handling - Invalid inputs, overflow, division by zero
- ✅ Edge Cases - Boundary values, special numbers, large integers
- ✅ Utility Functions - Comparison, validation, percentage calculations
Feature Tests (features/)
- ✅ Division Operations - Comprehensive division scenarios
- ✅ Edge Cases - Boundary conditions and error states
- ✅ Float Conversion - Float input/output validation
- ✅ Multiplication - Complex multiplication scenarios
- ✅ Normalize/Denormalize - Universal conversion and round-trip testing
- ✅ String Conversion - String parsing and formatting
- ✅ View Conversion - Display formatting and precision
Continuous Integration
The project uses GitHub Actions for automated testing:
- Automated Test Execution - Runs on every push and pull request
- Coverage Validation - Ensures 100% coverage is maintained
- Multi-environment Testing - Tests across different PHP configurations
- Quality Gates - Prevents merging code that breaks tests or reduces coverage
Contributing
We welcome contributions from the community! Whether you're fixing bugs, adding features, improving documentation, or reporting issues, your help makes this library better for everyone.
How to Contribute
🐛 Reporting Issues
Found a bug or have a feature request? Please open an issue with:
- Clear description of the problem or feature request
- Steps to reproduce (for bugs)
- Expected vs actual behavior
- PHP version and system information
- Code examples demonstrating the issue
🔧 Pull Requests
Ready to contribute code? We'd love your help! Please:
- Fork the repository and create a feature branch
- Write tests for any new functionality
- Ensure 100% coverage is maintained
- Follow PSR-12 coding standards
- Update documentation as needed
- Submit a pull request with a clear description
📋 Contribution Checklist
Before submitting a pull request, ensure:
- [ ] All tests pass:
./vendor/bin/phpunit - [ ] Feature tests pass:
./vendor/bin/behat - [ ] 100% code coverage maintained
- [ ] Code follows PSR-12 standards
- [ ] Documentation is updated
- [ ] CHANGELOG.md is updated (for notable changes)
🎯 Areas for Contribution
We especially welcome contributions in these areas:
- Performance optimizations for large number operations
- Additional mathematical operations (modulo, power, etc.)
- Documentation improvements and examples
- Bug fixes and edge case handling
- Platform compatibility testing
💡 Feature Requests
Have an idea for a new feature? We'd love to hear it! Consider:
- Mathematical operations that would benefit from precision handling
- Integration helpers for popular frameworks
- Performance improvements for specific use cases
- Developer experience enhancements
Development Setup
Code of Conduct
Please note that this project follows a Code of Conduct. By participating, you agree to:
- Be respectful and inclusive
- Focus on constructive feedback
- Help create a welcoming environment for all contributors
Getting Help
Need help getting started or have questions?
- 📖 Check the TESTING.md
- 🐛 Search existing issues
- 💬 Open a new issue for questions
- 📧 Contact the maintainers for complex queries
Thank you for contributing to IntPrecisionHelper! 🚀
License
MIT License
All versions of int-precision-helper with dependencies
ext-bcmath Version *