I'm currently working in a little porgram that calculates a formula for some numbers entered, the fact is I need the answer with some decimal values, but I've been unable to find a way to print my answer as a double or other similar type of variable with the information on the internet, it either produce an error or only prints the integer part of the answer.
func main() {
var m = 0
a := make([]int, 5)
for i := 0; i < 5; i++ {
fmt.Scan(&a[i])
}
m = a[0]*60 + a[2] + (a[4]/60)
fmt.Println(m)
}
Thanks in advance for any hint or help.
Integer division truncates the result towards zero. Use a floating-point result. For example, with minimal loss of accuracy,
package main
import "fmt"
func main() {
var m float64
a := make([]int64, 5)
for i := 0; i < 5; i++ {
_, err := fmt.Scan(&a[i])
if err != nil {
fmt.Println(err)
i--
}
}
fmt.Println(a)
m = float64((a[0]*60+a[2])*60+a[4]) / 60
fmt.Println(m)
}
Output:
2 3 4 5 6
[2 3 4 5 6]
124.1
use fmt.Printf function link C - printf function
import fmt
value := 2.2
fmt.Printf("%f", value)
You'll want to use a float64
rather than an int
if you're looking to use decimal places with numbers. Just be careful using them with currency.
Use float64, and convert all your ints into floats before calculations.
The following will give you decimal values.
m = float64(a[0])*60 + float64(a[2]) + (float64(a[4])/60)
But this will give ints.
m = float64(a[0]*60 + a[2] + (a[4]/60))