yii\i18n\Formatter::asPercent PHP Method

asPercent() public method

Formats the value as a percent number with "%" sign.
public asPercent ( mixed $value, integer $decimals = null, array $options = [], array $textOptions = [] ) : string
$value mixed the value to be formatted. It must be a factor e.g. `0.75` will result in `75%`.
$decimals integer the number of digits after the decimal point.
$options array optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
$textOptions array optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
return string the formatted result.
    public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $value = $this->normalizeNumericValue($value);
        if ($this->_intlLoaded) {
            $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
            if (($result = $f->format($value)) === false) {
                throw new InvalidParamException('Formatting percent value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
            }
            return $result;
        } else {
            if ($decimals === null) {
                $decimals = 0;
            }
            $value *= 100;
            return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
        }
    }

Usage Example

 public function testAsPercent()
 {
     $value = '123';
     $this->assertSame('12,300%', $this->formatter->asPercent($value));
     $value = '0.1234';
     $this->assertSame("12%", $this->formatter->asPercent($value));
     $value = '-0.009343';
     $this->assertSame("-1%", $this->formatter->asPercent($value));
     $this->assertSame($this->formatter->nullDisplay, $this->formatter->asPercent(null));
 }
All Usage Examples Of yii\i18n\Formatter::asPercent