#Does zig or lib have a function to round off float values up to a decimal?
1 messages · Page 1 of 1 (latest)
i dont think that's a correct implementation
also what about rounding to a negative number of digits?
isnt roundTo(123.456, -1) = 120 reasonable?
Never needed it
more important thing is that your implementation is incorrect
Not anymore
now it doesn't work for comptime_float
quite ugly but seems to work: https://godbolt.org/z/WosKKrqcY
const std = @import("std");
pub fn roundTo(value: anytype, place: u8) @TypeOf(value) {
if (place == 0) return @round(value);
const mod: @TypeOf(value) = @floatFromInt(place * 10);
return @round(value * mod) / mod;
}
pub fn roundToFixed(value: anytype, place: anytype) @TypeOf(value) {
// couldnt find a way to use std lib for thi...
and should be fairly efficient
you could probably make it a lot faster but should be within a few orders of magnitude of optimal
where is T defined?
oh my implementation doesnt work if value isnt comptime but exponent is
now it works with comptime ints too: https://godbolt.org/z/YYrE4rKfG
const std = @import("std");
pub fn roundTo(value: anytype, place: u8) @TypeOf(value) {
if (place == 0) return @round(value);
const mod: @TypeOf(value) = @floatFromInt(place * 10);
return @round(value * mod) / mod;
}
pub fn roundToFixed(value: anytype, place: anytype) @TypeOf(value) {
// couldnt find a way to use std lib for thi...
wait what am i doing it should just only work for powers of 10 lmao
yeah but what about negative values?
is a max of 127 enough?
right thats way beyond the precision
of anything >1
either way i think youve got enough ideas to make something that suits your usecase
glhf
np
is this rounding a bottleneck?