NumberHelper Integration

The CakeDecimal plugin extends the NumberHelper to work seamlessly with Decimal value objects. This ensures proper precision and scale handling in templates.

Setup Required: Add CakeDecimal.Number in your AppView to enable Decimal support.
See documentation for details.

1. format() - Basic Number Formatting

The helper automatically detects the scale from Decimal objects and formats them correctly.

$price = Decimal::create('1234.56');
echo $this->Number->format($price);
// Output: 1,234.56 (with automatic scale detection)
Result: 1,234.56
Decimal scale: 2

2. currency() - Currency Formatting

Format Decimal objects as currency with proper precision.

echo $this->Number->currency($price, 'USD');
echo $this->Number->currency($largePrice, 'EUR');
USD: $1,234.56
EUR: €9,876,543.21
GBP: £1,234.56

3. formatDelta() - Delta/Change Formatting

Display positive and negative changes with appropriate formatting and symbols.

echo $this->Number->formatDelta($delta);        // Positive change
echo $this->Number->formatDelta($negativeDelta); // Negative change
Positive: +15.75
Negative: -8.25

4. precision() - Custom Precision

Override the default scale with custom precision.

echo $this->Number->precision($price, 3);      // 3 decimal places
echo $this->Number->precision($price, 0);      // No decimals (rounded)
echo $this->Number->precision($smallNumber, 4); // 4 decimal places
3 places: 1,234.560
0 places: 1,235
4 places: 0.0050

5. toPercentage() - Percentage Formatting

Convert Decimal objects to percentage display.

echo $this->Number->toPercentage($percentage);
// Note: 0.875 = 87.5%
Result: 87.50%
Input value: 0.875

Advantages Over Float Casting

Why use the extended NumberHelper?
  • Automatic Scale Detection: The helper uses the Decimal object's internal scale instead of guessing
  • Precision Preservation: No loss of precision from float conversion
  • Consistent Output: Database field scale is maintained throughout the display layer
  • Type Safety: Works with Decimal objects, strings, floats, and integers

Comparison: Decimal vs Float

See how the extended NumberHelper maintains precision compared to float casting:

// With Decimal object
$decimal = Decimal::create('0.10');
echo $this->Number->format($decimal); // 0.10 (scale preserved)

// With float (loses trailing zero)
$float = 0.10;
echo $this->Number->format($float);   // 0.1 (scale lost)
Decimal: 0.10
Float: 0.1
Notice the Decimal preserves the .10 scale while float becomes .1

Send your feedback or bugreport!