Search code examples
type-conversionzig

Convert i32 into f32


How can I convert a i32 into a f32 in Zig Language?

I want to count appearances of values in a for loop and afterwards get the percentages in a smooth floating number.

var partial : i32 = 0;
var total : i32 = 2000;
  

for (arr[0..total]) |value| {
    if(value < 200) inCircle = inCircle +  1;
}

const result = partial / total;

Solution

  • Zig 0.11+

    Use @floatFromInt:

    const result = @as(f32, @floatFromInt(partial)) / @as(f32, @floatFromInt(total));
    

    If you're confused about the need to use @as: see Result Location Semantics or this answer.

    Zig 0.10

    You need to use @intToFloat function. Like this:

    const result = @intToFloat(f32, partial) / @intToFloat(f32, total);