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


(GBNepal) #1

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),
}


(Norbert Melzer) #2

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…

https://duckduckgo.com/?q=why+do+not+use+float+for+money&t=h_&ia=web

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…