Freemarker Decimal Truncation

<#-- Initialize the formatted dimensions string -->
<#assign formatted_dimensions = "" />


<#-- Function to truncate the decimal part to a maximum of 3 places without rounding -->
<#function truncateTo3DecimalPlaces number>
    <#-- Convert the number to a string without rounding and split at the decimal point -->
    <#assign numberString = number?string("0.0################") />
    <#assign parts = numberString?split(".") />


    <#if parts?size == 1>
        <#-- If there is no decimal part, return the integer part -->
        <#return parts[0] />
    <#else>
        <#-- Get the integer part and decimal part -->
        <#assign integerPart = parts[0] />
        <#assign decimalPart = parts[1] />


        <#-- Truncate the decimal part to a maximum of 3 characters without rounding -->
        <#if decimalPart?length > 3>
            <#assign truncatedDecimalPart = decimalPart?substring(0, 3) />
        <#else>
            <#assign truncatedDecimalPart = decimalPart />
        </#if>


        <#-- Combine the integer part and the truncated decimal part -->
        <#return integerPart + "." + truncatedDecimalPart />
    </#if>
</#function>


<#-- Loop through each dimension part -->
<#list dimension_parts as part>
    <#-- Convert to number and truncate the decimal part to a maximum of 3 places -->
    <#assign part_number = part?number />
    <#assign formatted_part = truncateTo3DecimalPlaces(part_number) />


    <#-- Append formatted part to the result -->
    <#if part_has_next>
        <#assign formatted_dimensions = formatted_dimensions + formatted_part + "" x " />
    <#else>
        <#assign formatted_dimensions = formatted_dimensions + formatted_part + """ />
    </#if>
</#list>


<#-- Output the formatted string -->
${formatted_dimensions}


Leave a comment

Your email address will not be published. Required fields are marked *