decimal icon indicating copy to clipboard operation
decimal copied to clipboard

Implement fmt.Formatter

Open deitrix opened this issue 2 years ago • 3 comments

It would be nice if Decimal types implemented the fmt.Formatter interface to allow the use of standard fmt verbs/flags when formatting decimals to strings.

For example:

fmt.Printf("%.2f", decimal.RequireFromString("3.14"))

Would be equivalent to:

fmt.Printf("%s", decimal.RequireFromString("3.14").StringFixed(2))

There are a number of other verbs/flags that could be implemented which can be seen here

deitrix avatar Aug 29 '23 13:08 deitrix

That would be an amazing addition to the library, thanks for the suggestion! :3 I won't be able to implement it before the 1.4 release, but I will add it to the backlog. Thanks!

mwoss avatar Dec 30 '23 14:12 mwoss

@mwoss Hi, I've interested in this issue. Indeed, we would be good as if we used fmt.Formatter. So I started this implementation, I have two questions. First, what should we do if it has the width of views into the format indicator? Because we cannot see the width of view above the example such as 5 of %5.2f , I don't see what should we consider the width of view?

fmt.Printf("%5.2f", decimal.RequireFromString("3.14")) 

Second, the concept of the Decimal's places, it can be placed with a negative number but what should we represent a negative number on the format indicator?

https://pkg.go.dev/fmt#hdr-Printing

u5surf avatar Apr 23 '24 10:04 u5surf

Hi @u5surf! Thanks for working on this, I greatly appreciate that! :3 Answering your questions:

What should we consider the width of view?

I think in our case the format width parameter should be treated as padding. So in the above case you gave we should add spaces to the result on the left. There are other flags like 0 when we should fill those spaces with 0 instead of spaces.

The concept of the Decimal's places, it can be placed with a negative number but what should we represent a negative number on the format indicator?

In terms of formatting, I believe we should only support positive values for precision format parameters. I know the library itself supports negative places/precision, but for formatting, I don't think it's something necessary. If there will be a community need for that feature, we could add this later. :D

mwoss avatar Apr 28 '24 11:04 mwoss