Yii v2 snippet guide II

Comparing #30 with #31

Revision #31 was created by rackycz rackycz on Oct 3, 2020, 4:25:27 PM.

Decimal Integer formatter

Content

[...]
- https://github.com/tecnickcom/tc-lib-pdf
- composer require tecnickcom/tc-lib-pdf:dev-master
- use Com\Tecnick\Pdf\TCPDF;
- $pdf = new TCPDF();

**Custom formatter - asDecimalOrInteger **
 
---
 
If I generate a PDF-invoice it contains many numbers and it is nice to print them as integers when decimals are not needed. For example number 24 looks better and saves space compared to 24.00. So I created such a formatter. Original inspiration was found here:
 
 
- https://stackoverflow.com/questions/46089960/yii2-formatter-create-custom-format
 
 
My formatter looks like this:
 
 
```php
 
<?php
 
 
namespace app\myHelpers;
 
 
class MyFormatter extends \yii\i18n\Formatter {
 
 
  public function asDecimalOrInteger($value) {
 
    $intStr = (string) (int) $value; // 24.56 => "24" or 24 => "24"
 
    if ($intStr === (string) $value) {
 
      // If input was integer, we are comparing strings "24" and "24"
 
      return $this->asInteger($value);
 
    }
 
    if (( $intStr . '.00' === (string) $value)) {
 
      // If the input was decimal, but decimals were all zeros, it is an integer.
 
      return $this->asInteger($value);
 
    }
 
    // All other situations
 
    return $this->asDecimal($value);
 
  }
 
 
}
 
```