I have a variable of type Float64 that can have fractional digits or not. For example, it could be
4, 4.5, 4.75 etc.

I need to return its value as a string. So I do:

myvar = 4.f_64
myvar_str = "#{myvar}"
puts myvar_str ## this prints 4.0. Can I have it print as 4 (without the 0)?

I looked at decimal_places option. But it appears that would not work since I want 4.3 to be printed as 4.3. I want 4.0 to be printed as 4. How can I do that?

Thank you @Blacksmoke16. I have not looked at the source code, so this is not about implementation of only_significant. But, mathematically speaking, the notion of significance is very confusing. I don’t understand it. According to https://www.purplemath.com/modules/rounding2.htm the zero in 4.0 is significant. But the zeroes in 1000 are not significant. Weird!

If possible, I don’t want to round the numbers when there are decimal places, like this one does. Are there some circumstances in which my solution will not work?

Have a look at the documentation for Kernel::sprintf first. You should also know that the format string is based on printf(3), from the C language and has been around for decades. You can also look at Wikipedia though it is actually about C, not Crystal, and also includes lots of extensions which do not apply to Crystal. It does say about “g”:

This type differs slightly from fixed-point notation in that insignificant zeroes to the right of the decimal point are not included. Also, the decimal point is not included on whole numbers.

which is a better description than Crystal (or Ruby’s) documentation.