mirror of
https://github.com/taigrr/wtf
synced 2025-01-18 04:03:14 -08:00
WTF-897 Exchange Rate improvements
Allows the user to set the precision for their exchange rate values. Config setting: ``` exchangerates: precision: 3 ``` Default is `7`. Also aligns converted values along the decimal place for improved aesthetics. Signed-off-by: Chris Cummer <chriscummer@me.com>
This commit is contained in:
14
wtf/numbers.go
Normal file
14
wtf/numbers.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package wtf
|
||||
|
||||
import "math"
|
||||
|
||||
// Round rounds a float to an integer
|
||||
func Round(num float64) int {
|
||||
return int(num + math.Copysign(0.5, num))
|
||||
}
|
||||
|
||||
// TruncateFloat64 truncates the decimal places of a float64 to the specified precision
|
||||
func TruncateFloat64(num float64, precision int) float64 {
|
||||
output := math.Pow(10, float64(precision))
|
||||
return float64(Round(num*output)) / output
|
||||
}
|
||||
78
wtf/numbers_test.go
Normal file
78
wtf/numbers_test.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package wtf
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
||||
func Test_Round(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input float64
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "negative",
|
||||
input: -3,
|
||||
expected: -3,
|
||||
},
|
||||
{
|
||||
name: "integer",
|
||||
input: 3,
|
||||
expected: 3,
|
||||
},
|
||||
{
|
||||
name: "float down",
|
||||
input: 3.123456,
|
||||
expected: 3,
|
||||
},
|
||||
{
|
||||
name: "float up",
|
||||
input: 3.998786,
|
||||
expected: 4,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
actual := Round(tt.input)
|
||||
assert.Equal(t, tt.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_TruncateFloat(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input float64
|
||||
precision int
|
||||
expected float64
|
||||
}{
|
||||
{
|
||||
name: "negative precision",
|
||||
input: 23.234567,
|
||||
precision: -2,
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "zero precision",
|
||||
input: 23.234567,
|
||||
precision: 0,
|
||||
expected: 23,
|
||||
},
|
||||
{
|
||||
name: "positive precision",
|
||||
input: 23.234567,
|
||||
precision: 2,
|
||||
expected: 23.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
actual := TruncateFloat64(tt.input, tt.precision)
|
||||
assert.Equal(t, tt.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user