When displaying data within the grid UI component in the Magento 2 admin, there might be some data that is stored by Magento as a decimal and contains trailing zeros. You might want to remove decimals from grid UI component columns to display your data more neatly.
A classic example of this occurring is within the cataloginventory_stock_item
database table involving the qty
and min_qty
columns.
If you have joined quantity information within your grid and are seeing your quantity-related columns appearing as decimals, there is a simple solution to fix this problem.
When defining your columns within your UI component XML file, you can add a column-specific class.
<column name="qty" class="[Vendor]\[Module]\Ui\Component\Listing\Columns\Quantity"> <settings> <filter>text</filter> <label translate="true">Current Qty</label> </settings> </column>
The column class extends from Magento\Ui\Component\Listing\Columns\Column
and contains a prepareDataSource()
method.
<?php namespace [Vendor]\[Module]\Ui\Component\Listing\Columns; class Quantity extends \Magento\Ui\Component\Listing\Columns\Column { /** * Column name */ const NAME = 'column.qty'; /** * Prepare Data Source * * @param array $dataSource * @return array */ public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { $fieldName = $this->getData('name'); foreach ($dataSource['data']['items'] as & $item) { if (isset($item[$fieldName])) { $item[$fieldName] = (int)$item[$fieldName]; } } } return $dataSource; } }
Within this method, a foreach around the data within the column is made, and if the data is set, the data is cast as an integer.
This simple conversion will allow you to display any decimal data as an integer, and works particularly well with Magento quantities.
Note: This article is based on Magento Open Source version 2.2.