Revision #31 has been created by rackycz on Oct 3, 2020, 4:25:27 PM with the memo:
Decimal Integer formatter
« previous (#30) next (#32) »
Changes
Title
unchanged
Yii v2 snippet guide II
Category
unchanged
Tutorials
Yii version
unchanged
2.0
Tags
unchanged
tutorial,beginner,yii2,snippets
Content
changed
[...]
- 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);
}
}
```