GLSL Learning

GLSL built-in function

fract()

Returns the fractional part of x, computed as x - floor(x), always in the range 0.0 to 1.0.

Syntax

float fract(float x)
vec2 fract(vec2 x)
vec3 fract(vec3 x)
vec4 fract(vec4 x)

Parameters

x
The value to take the fractional part of. Vectors are processed per component.

Return value

A value of the same type as x, each component in [0.0, 1.0).

Live example

Edit the code and the preview updates as you type.

How it works

fract(x) keeps only what comes after the decimal point:

  • fract(2.75) is 0.75
  • fract(3.0) is 0.0
  • fract(-0.25) is 0.75 (because it is x - floor(x), and floor(-0.25) is -1.0)

The trick is to scale first. uv goes from 0 to 1 once across the canvas. uv * 5.0 goes from 0 to 5, and fract of that restarts at 0 every time it crosses a whole number. The result is five copies of the 0..1 range, which the example shows as a 5 x 5 grid of gradients.

Typical uses

  • Tiling: fract(uv * n) gives every tile its own local 0..1 coordinates, so one shape repeats across the canvas.
  • Looping animation: fract(u_time * 0.5) ramps from 0 to 1 every two seconds and jumps back.
  • Hash functions: fract(sin(x) * 43758.5453) is the classic one-line pseudo-random number.

Common mistakes

  • Forgetting that the jump from almost 1 back to 0 is a hard edge. If you need a smooth loop, use sin or abs(fract(x) * 2.0 - 1.0) for a triangle wave.
  • Combining fract and floor with different scale factors. The tile index is floor(uv * n) and the local coordinate is fract(uv * n) with the same n.

Related functions

Tutorials that use fract()