web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :

Convert Quantity Between Units Using Unit Symbols in D365FO

dasdasd Profile Picture dasdasd 841

 In Dynamics 365 Finance & Operations (D365FO), unit conversion is a common requirement when working with sales, purchasing, inventory, and warehouse processes.

Instead of hardcoding conversion factors, we can use the standard UnitOfMeasureConversion table to retrieve the product-specific conversion factor.

The following reusable X++ method converts a quantity from one unit to another using the configured conversion setup.

X++ Code

private Qty convertQtyByUnitSymbols(
    ItemId              _itemId,
    UnitOfMeasureSymbol _fromSymbol,
    UnitOfMeasureSymbol _toSymbol,
    Qty                 _qty)
{
    InventTable            inventTable = InventTable::find(_itemId);
    EcoResProduct          product     = inventTable.Product();
    UnitOfMeasure          fromUnit    = UnitOfMeasure::findBySymbol(_fromSymbol);
    UnitOfMeasure          toUnit      = UnitOfMeasure::findBySymbol(_toSymbol);
    UnitOfMeasureConversion conversion;
    Qty                     result      = _qty;

    if (!product.RecId || !fromUnit.RecId || !toUnit.RecId)
    {
        return result;
    }

    // Ensure the item's inventory unit matches the "from" unit
    if (inventTable.inventUnitId() != fromUnit.Symbol)
    {
        return result;
    }

    select firstonly Factor from conversion
        where conversion.Product           == product.RecId
           && conversion.FromUnitOfMeasure == fromUnit.RecId
           && conversion.ToUnitOfMeasure   == toUnit.RecId;

    if (conversion.RecId && conversion.Factor != 0)
    {
        result = _qty * conversion.Factor;
    }

    return result;
}

This approach keeps the conversion simple, reusable, and configuration-driven, using the standard D365FO unit conversion setup rather than hardcoded conversion factors.


This was originally posted here.

Comments

*This post is locked for comments