Go one liner function for float to string conversion instead of typing fmt.Sprintf() for multiple places

revenue := formatFloat(10000.4548)
expenses := format(2555.1224)
and similar formatting needed for dozen more attributes

What do you prefer - fmt.Sprintf() for each attribute or function that takes in float and returns formatted string? I like function even though it is just one liner because you are typing/copy(paste) less:) and also if decimal places is needed to be updated to 4(not likely, just saying), you can manage it in function.

// formats float to string with 2 decimal places
func formatFloat(floatValue float) {
return fmt.Sprintf("%.2f", floatValue),
}

2 Likes

Is this for money? Please don’t use float or any other floating point type. Use a proper decimal or even money type.

DDG will give you enough to read…

PS: I rarely convert my data to string, I usually print them directly (or write to a descriptor) using Printf/Fprintf. Convertig it to a string makes me loose all the precious information…

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.