There's probably some more elegant way to do this with arithmetic and/or bit fiddling, but here's one approach that takes advantage of the "FloatToString" function handling this case automagically. It should at least solve your example case.
PHP Code:
#include <sourcemod>
// Parameters:
// f - Floating point number to convert.
// n - At how many decimal points to truncate at.
// out - Buffer to store string in.
// maxlen - Maximum length of string buffer.
// Return value: Number of characters written to the buffer, not including the null terminator.
int FloatToStringTruncate(float f, int n, char[] out, int maxlen)
{
int res = FloatToString(FloatFraction(f), out, maxlen);
int cutoff = 3 + n;
if (cutoff >= maxlen)
{
return res;
}
out[cutoff] = '\0';
return Format(out, cutoff, "%d%s%s",
RoundToFloor(f),
n <= 0 ? "" : ".",
out[n <= 0 ? 3 : 2]
);
}
public void OnPluginStart()
{
float f = 0.04;
PrintToServer("Plain: %f", f);
PrintToServer("Format-class functions: %.2f", f);
char buffer[32];
FloatToStringTruncate(f, 2, buffer, sizeof(buffer));
PrintToServer("FloatToStringTruncate: %s", buffer);
}
...or whatever "truncate at n chars after the decimal point" method you'd wanna use.
This outputs:
Quote:
Plain: 0.039999
Format-class functions: 0.03
FloatToStringTruncate: 0.04
|