1

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;
Marian Klösler
  • 620
  • 8
  • 22

1 Answers1

3

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);
sigod
  • 3,514
  • 2
  • 21
  • 44