Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: A simple way to round decimal? #3

Open
asv opened this issue Sep 25, 2022 · 3 comments
Open

Question: A simple way to round decimal? #3

asv opened this issue Sep 25, 2022 · 3 comments

Comments

@asv
Copy link

asv commented Sep 25, 2022

Thanks for the library!
Can you please tell me how to round decimal from 4 to 2 decimal places?

For example 1234.4567 -> 1234.46.

@nikolaydubina
Copy link
Owner

nikolaydubina commented Sep 26, 2022

Is this over the wire? If you have JSON number (string) {"stock": 1234.4567}, then this lib with fp3 will discard 7 and keep 1234.456. Similar happens with direct use of ParseFixedPointDecimal. The current implementation of parser disregards all digits after specified number (for fp3 it is 3). If you need more, then need to define new type fp4 or if it is dynamic can reference to https://github.com/nikolaydubina/fpmoney.

If it is already parsed number output of ParseFixedPointDecimal, then you can round with any policy, but have to do yourself, it is not implemented here.

If it is fp3.Decimal and we want to reduce to 2 decimals, there is no function to export internal value yet. But feel free to add! There is reversed function tho FromIntScaled.

Also, if it is (a fp3.Decimal) Round(n int) fp3.Decimal also nice to have!

@asv
Copy link
Author

asv commented Sep 27, 2022

I thought that decimal rounding is a complex computer science problem and should be solved by professionals... ;) But if you tell me which direction to dig, I can try to write a patch.

@nikolaydubina
Copy link
Owner

haha. yeah let's improve rounding for this pkg! Can be in separate PRs:

  1. func (v fp3.Decimal) IntUnscaled() int64 - returns internal raw value without scaling.
  2. (a fp3.Decimal) Round(n int) fp3.Decimal - round half up number of decimal points (e.g. 0.5 Round(1) -> 1.0; 0.001 Round(3) -> 0.001)
  3. global pkg level var for policy of fp3 pkg parsing + new func ParseFixedPointDecimalWithRounding that uses it. be default original behavior = "discard digits without rounding". This is a bit more complex.

For all of these need fuzz test (with couple unit tests or scenarios).

Thanks for interest! 💪🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants