Intrinsics1 min read
trunc
Rounds a value toward zero.
Reading Time
1 min
Word Count
127
Sections
12
Try It Live
Test trunc in a live shader
Open the playground, start from a visual preset, and wire trunc into the fragment stage to see how it behaves with real values.
Open PlaygroundThe trunc function removes the fractional part of a floating-point value. Unlike floor and ceil, it always rounds toward zero.
Live Demo
Signature
bwsl
trunc :: (T x) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | The input value |
Return Value
Returns x rounded toward zero.
Example
bwsl
pipeline PixelSnap {
fragment {
float2 centered = input.uv * 16.0 - 8.0;
// Snap both positive and negative offsets toward zero
float2 snapped = trunc(centered);
float2 cell = snapped / 8.0;
float3 color = float3(cell.x * 0.5 + 0.5, cell.y * 0.5 + 0.5, 0.8);
output.color = float4(color, 1.0);
}
}Common Use Cases
Integer Part Extraction
bwsl
// Drop the fractional part while preserving the sign direction
float integerPart = trunc(value);Symmetric Quantization
bwsl
// Quantize offsets symmetrically around zero
float2 steppedOffset = trunc(offset / stepSize) * stepSize;Sprite Cell Selection
bwsl
// Select a sprite atlas cell from normalized coordinates
int2 cell = int2(trunc(uv * atlasGrid));Signed Distance Banding
bwsl
// Build bands that behave consistently on both sides of zero
float band = trunc(signedDistance * bands) / bands;Negative Values
trunc(-1.7) returns -1.0, while floor(-1.7) returns -2.0. Use trunc when you want the fractional part removed without rounding away from zero.
Compiled Output
When compiled to GLSL:
glsl
trunc(x)
When compiled to HLSL:
hlsl
trunc(x)
When compiled to Metal:
metal
trunc(x)