69 lines
1.4 KiB
Go
69 lines
1.4 KiB
Go
package converter
|
|
|
|
import "fmt"
|
|
import "log"
|
|
import "strconv"
|
|
import "strings"
|
|
|
|
const (
|
|
markerMiles = "mi"
|
|
markerKm = "km"
|
|
markerFeet = "ft"
|
|
markerMeter = "m"
|
|
MilesToKm float64 = 1.609344
|
|
FeetsToMeters float64 = 3.28084
|
|
)
|
|
|
|
var (
|
|
inUnit string
|
|
inVal float64
|
|
asMeter float64
|
|
err error
|
|
convVal float64
|
|
)
|
|
|
|
func Convert(input, convTo string) string {
|
|
switch {
|
|
case strings.HasSuffix(input, markerKm):
|
|
inUnit = markerKm
|
|
case strings.HasSuffix(input, markerFeet):
|
|
inUnit = markerFeet
|
|
case strings.HasSuffix(input, markerMeter):
|
|
inUnit = markerMeter
|
|
case strings.HasSuffix(input, markerMiles):
|
|
inUnit = markerMiles
|
|
default:
|
|
log.Fatalln("Invalid input:", input)
|
|
}
|
|
inVal, err = strconv.ParseFloat(input[:len(input)-len(inUnit)], 64)
|
|
if err != nil {
|
|
log.Fatalln("Invalid input number", err)
|
|
}
|
|
|
|
switch inUnit {
|
|
case markerMiles:
|
|
asMeter = inVal * MilesToKm * 1000
|
|
case markerKm:
|
|
asMeter = inVal * 1000
|
|
case markerFeet:
|
|
asMeter = inVal * FeetsToMeters
|
|
case markerMeter:
|
|
asMeter = inVal
|
|
}
|
|
|
|
switch convTo {
|
|
case markerMiles:
|
|
convVal = asMeter / (MilesToKm * 1000)
|
|
case markerKm:
|
|
convVal = asMeter / 1000
|
|
case markerFeet:
|
|
convVal = asMeter / FeetsToMeters
|
|
case markerMeter:
|
|
convVal = asMeter
|
|
default:
|
|
log.Fatalln("Invalid unit: " + convTo)
|
|
}
|
|
|
|
return fmt.Sprintf("%.2f%s", convVal, convTo)
|
|
}
|