The Problem: In Some Dialects, Performing a Calculation between Integers Always Returns an Integer
In certain dialects, including Postgres and Redshift, performing a calculation between integers (like dividing counts) will return an integer even if the result would be a decimal in normal math. You might make measures like this:
measure: sold_ratio {
type: number
sql: ${sold_count} / ${total_count} ;;
value_format: "0.00" # Number with exactly 2 decimals (1.23)
}
measure: sold_percent {
type: number
sql: 100 * ${sold_count} / ${count} ;;
value_format: "0.00"
}
In the data table, however, the sold_ratio
column is returning zero, and the sold_percent
column does not have its decimal places populated. If we do the math, it becomes clear that this is not correct.
The Solution: Cast Field as a Floating-Point Number
If the calculation is multiplied by a non-integer, the values will cast as floats, and decimals will be returned as expected. You can multiply the numerator by a decimal number (like 1.0 or 100.0) to force SQL into returning a decimal result:
measure: sold_ratio {
type: number
sql: 1.0 * ${sold_count} / ${total_count};;
value_format: "0.00"
}
measure: sold_percent {
type: number
sql: 100.0 * ${sold_count} / ${count};;
value_format: "0.00"
}