Find decimal count from shopspring decimal library - go

I am using github.com/shopspring/decimal for decimal related operations in golang instead of float for actual precision.
I have a requirement to find the decimal count for a decimal library value.
eg:-
price := decimal.NewFromFloat(0.00355)
fmt.Println("Price:", price) // Price:0.00355
This is how I use the decimal. So now I want to count the number of decimals from the same decimal.
In the above example the decimal count would be 5 since there are five decimal points.
Checked the docs but couldn't find the right operation for this. Can somebody help with this?
Thanks in advance.

You can convert decimal value to string, then count number of char after point ..
0.00355 => "0.00355" => count=5

Wouldn't you just use decimal.Exponent() and ask the number what its scale is?
https://goplay.tools/snippet/9Y6BP1dcOuA
package main
import (
"fmt"
"github.com/shopspring/decimal"
)
func main() {
x := decimal.NewFromFloat(123.456789)
s := x.Exponent()
fmt.Printf("decimal value %v has a scale of %v\n", x, s)
}
Which yields
decimal value 123.456789 has a scale of -6

Related

Go/Golang: how to extract least significant digits from big.Float?

In Go/Golang I have a variable of type big.Float with an (arbitrary) precision of 3,324,000 to represent a decimal number of 1,000,000 digits. It's the result of an iteration to calculate pi.
Now I want to print out the least significant 100 digits, i.e. digits 999,900 to 1,000,000.
I tried to convert the variable to a string by using fmt.Sprintf() and big.Text(). However, both functions consume a lot of processing time which gets unacceptable (many hours and even days) when further raising the precision.
I'm searching for some functions which extract the last 100 (decimal) digits of the variable.
Thanks in advance for your kind support.
The standard library doesn't provide a function to return those digits efficiently, but you can calculate them.
It is more efficient to isolate the digits you are interested in and print them. This avoids excessive calculations of an extremely large number to determine each individual digit.
The code below shows a way it can be done. You will need to ensure you have enough precision to generate them accurately.
package main
import (
"fmt"
"math"
"math/big"
)
func main() {
// Replace with larger calculation.
pi := big.NewFloat(math.Pi)
const (
// Pi: 3.1415926535897932...
// Output: 5926535897
digitOffset = 3
digitLength = 10
)
// Move the desired digits to the right side of the decimal point.
mult := pow(10, digitOffset)
digits := new(big.Float).Mul(pi, mult)
// Remove the integer component.
digits.Sub(digits, trunc(digits))
// Move the digits to the left of the decimal point, and truncate
// to an integer representing the desired digits.
// This avoids undesirable rounding if you simply print the N
// digits after the decimal point.
mult = pow(10, digitLength)
digits.Mul(digits, mult)
digits = trunc(digits)
// Display the next 'digitLength' digits. Zero padded.
fmt.Printf("%0*.0f\n", digitLength, digits)
}
// trunc returns the integer component.
func trunc(n *big.Float) *big.Float {
intPart, accuracy := n.Int(nil)
_ = accuracy
return new(big.Float).SetInt(intPart)
}
// pow calculates n^idx.
func pow(n, idx int64) *big.Float {
if idx < 0 {
panic("invalid negative exponent")
}
result := new(big.Int).Exp(big.NewInt(n), big.NewInt(idx), nil)
return new(big.Float).SetInt(result)
}

Divide 2 big.Floats in go and preserve the resulting decimal

I have 2 big.Float numbers in go.
x. 93214.310998100256907925
y. 1.954478300965909786
I want to find out what percent of x y is. This should be around 0.0020967578%. The issue comes when dividing these 2 big floats the answer is always 0.xxx but the method returns 2.09675776180520477879426e-05. Any ideas to fix this? I have tried converting to a string then back but that isn't another rabbit hole I won't include because I wasn't able to accomplish anything with it. I feel like there is a method to do this I am missing. I really only need 7 decimals of precision of that helps.
Why do you need big.Float? Even float32 seem to be fine:
package main
import "fmt"
func percent(y, x float32) float32 {
return y / x * 100
}
func main() {
p := percent(1.954478300965909786, 93214.310998100256907925)
fmt.Println(p) // 0.0020967575
}

big.Float SetPrec weird behaviour

After doing some calculations using big.Float in golang, I am setting the precision to 2.
And even thou the number is just a simple 10, after setting the precision it is 8.
package main
import (
"fmt"
"math/big"
)
func main() {
cost := big.NewFloat(10)
fmt.Println("COST NOW", cost)
perKWh := big.NewFloat(0)
cost.Add(cost, perKWh)
fmt.Println("COST ", cost.String())
perMinute := big.NewFloat(0)
cost.Add(cost, perMinute)
fmt.Println("COST ", cost.String())
discountAmount := big.NewFloat(0)
cost.Sub(cost, discountAmount)
floatCos, _ := cost.Float64()
fmt.Println(fmt.Sprintf("COST FLOAT %v", floatCos))
cost.SetPrec(2)
fmt.Println("COST ", cost.String())
}
Check playground example here: https://play.golang.org/p/JmCRXkD5u49
Would like to understand why
From the fine manual:
type Float
[...]
Each Float value also has a precision, rounding mode, and accuracy. The precision is the maximum number of mantissa bits available to represent the value. The rounding mode specifies how a result should be rounded to fit into the mantissa bits, and accuracy describes the rounding error with respect to the exact result.
And big.Float is represented internally as:
sign × mantissa × 2**exponent
When you call SetPrec you're setting the number of bits available for the mantissa, not the number of digits of precision in the decimal representation of the number.
You can't represent decimal 10 (1010 binary) in two bits of mantissa so it rounds to decimal 8 (1000 binary) which can fit into 2 bits. You need at least three bits to store the 101 part of decimal 10. 8 can fit into a single bit of mantissa so you'll see the same 8 if you say cost.SetPrec(1).
You need to be thinking in terms of binary when using the big package.
First, discard all the irrelevant code. Next, print useful diagnostic information.
package main
import (
"fmt"
"math/big"
)
func main() {
cost := big.NewFloat(10)
fmt.Println("Cost ", cost.String())
fmt.Println("Prec", cost.Prec())
fmt.Println("MinPrec", cost.MinPrec())
fmt.Println("Mode", cost.Mode())
cost.SetPrec(2)
fmt.Println("Prec", cost.Prec())
fmt.Println("Accuracy", cost.Acc())
fmt.Println("Cost ", cost.String())
}
Output:
Cost 10
Prec 53
MinPrec 3
Mode ToNearestEven
Prec 2
Accuracy Below
Cost 8
Round 10 to the nearest even number that can be represented in an sign, exponent, and a 2-bit mantissa and you get 8.
Rounding ToNearestEven is IEE754 rounding. Round to nearest, ties to even – rounds to the nearest value; if the number falls midway it is rounded to the nearest value with an even (zero) least significant bit.

Is there any standard library to convert float64 to string with fix width with maximum number of significant digits?

Imagine for printing in a 12 fixed width table we need printing float64 numbers:
fmt.Printf("%12.6g\n", 9.405090880450127e+119) //"9.40509e+119"
fmt.Printf("%12.6g\n", 0.1234567890123) //" 0.123457"
fmt.Printf("%12.6g\n", 123456789012.0) //" 1.23457e+11"
We prefer 0.1234567890 to " 0.123457" we lose 6 significant digits.
We prefer 123456789012 to " 1.23457e+11" we lose 6 significant digits.
Is there any standard library to convert float64 to string with fix width with maximum number of significant digits?
Thanks in Advance.
Basically you have 2 output formats: either a scientific notation or a regular form. The turning point between those 2 formats is 1e12.
So you can branch if x >= 1e12. In both branches you may do a formatting with 0 fraction digits to see how long the number will be, so you can calculate how many fraction digits will fit in for 12 width, and so you can construct the final format string, using the calculated precision.
The pre-check is required in the scientific notation too (%g), because the width of exponent may vary (e.g. e+1, e+10, e+100).
Here is an example implementation. This is to get you started, but it does not mean to handle all cases, and it is not the most efficient solution (but relatively simple and does the job):
// format12 formats x to be 12 chars long.
func format12(x float64) string {
if x >= 1e12 {
// Check to see how many fraction digits fit in:
s := fmt.Sprintf("%.g", x)
format := fmt.Sprintf("%%12.%dg", 12-len(s))
return fmt.Sprintf(format, x)
}
// Check to see how many fraction digits fit in:
s := fmt.Sprintf("%.0f", x)
if len(s) == 12 {
return s
}
format := fmt.Sprintf("%%%d.%df", len(s), 12-len(s)-1)
return fmt.Sprintf(format, x)
}
Testing it:
fs := []float64{0, 1234.567890123, 0.1234567890123, 123456789012.0, 1234567890123.0,
9.405090880450127e+9, 9.405090880450127e+19, 9.405090880450127e+119}
for _, f := range fs {
fmt.Println(format12(f))
}
Output (try it on the Go Playground):
0.0000000000
0.1234567890
1234.5678901
123456789012
1.234568e+12
9405090880.5
9.405091e+19
9.40509e+119

GO: manipulating random generated float64

I was wondering if we can specify to the random generator to how many numbers should be generated after the point decimal?
Example of default behaviour:
fmt.Println(rand.float64())
Would print out the number 0.6046602879796196
Desired behaviour:
fmt.Println(rand.float64(4))
Would then print out the number 0.6047.
Does this functionality already exist in GO or would I have to implement it myself ?
Thank you!
It sounds like only the string representation is important to you, and the fmt package does provide that for you:
fmt.Printf("%1.4f", rand.Float64())
So yes, you would still need to wrap this call to specify the number of digits after the decimal point.
func RandomDigits(number int) string {
return fmt.Sprintf("%1." + strconv.Itoa(number) + "f", rand.Float64())
}
I don't know of such function, however it is easy to implement by yourself (play):
// Truncate the number x to n decimal places
//
// +- Inf -> +- Inf; NaN -> NaN
func truncate(x float64, n int) float64 {
return math.Trunc(x * math.Pow(10, float64(n))) * math.Pow(10, -float64(n))
}
Shift the number n decimal places to the left, truncate decimal places, shift the number n places to the right.
In case you want to present your number to the user then you will, at one point, convert the number
to a string. When you do that, you should not use this method and instead use string formatting as pointed
out by Tyson. For example, as floating point numbers are imprecise there might be rounding errors:
truncate(0.9405090880450124,3) // 0.9400000000000001

Resources