Golang : Calculate percentage change of two values
Here is a simple example on how to calculate the percentage change from two numbers. If the result is positive number, then it is percentage increase, if negative then it is percentage decrease.
Very useful in displaying data to illustrate a mathematical point of view, such as a decrease in population or increase in the number of certain species.
Here you go!
package main
import (
"fmt"
)
func PercentageChange(old, new int) (delta float64) {
diff := float64(new - old)
delta = (diff / float64(old)) * 100
return
}
func main() {
fmt.Printf("Old : 500, New : 500 Change : %0.2f %% \n", PercentageChange(500, 500))
// anything divided by 0 will become infinity
fmt.Printf("Old : 0, New : 50 Change : %0.2f %% \n", PercentageChange(0, 50))
fmt.Printf("Old : 100, New : 30 Change : %0.2f %% \n", PercentageChange(100, 30))
fmt.Printf("Old : 1000, New : 830 Change : %0.2f %% \n", PercentageChange(1000, 830))
fmt.Printf("Old : 5, New : 3 Change : %0.2f %% \n", PercentageChange(5, 3))
fmt.Printf("Old : -15, New : 3 Change : %0.2f %% \n", PercentageChange(-15, 3))
fmt.Printf("Old : 100, New : 130 Change : %0.2f %% \n", PercentageChange(100, 130))
}
Output:
Old : 500, New : 500 Change : 0.00 %
Old : 0, New : 50 Change : +Inf %
Old : 100, New : 30 Change : -70.00 %
Old : 1000, New : 830 Change : -17.00 %
Old : 5, New : 3 Change : -40.00 %
Old : -15, New : 3 Change : -120.00 %
Old : 100, New : 130 Change : 30.00 %
Reference:
See also : Golang : Create and shuffle deck of cards example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.5k Golang : Sieve of Eratosthenes algorithm
+21.4k Golang : Join arrays or slices example
+5.3k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+11.6k Golang : Decompress zlib file example
+16.3k Golang : Gzip file example
+8.5k Golang : GMail API create and send draft with simple upload attachment example
+33.3k Golang : Create x509 certificate, private and public keys
+7.6k Golang : Check from web if Go application is running or not
+10.1k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+9.5k Golang : Sort and reverse sort a slice of integers
+11.1k Golang : Generate DSA private, public key and PEM files example
+8.4k Golang : Random integer with rand.Seed() within a given range