Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang how can I multiply a integer and a float

Tags:

go

I am trying to resize the dimensions of an image but am getting a constant 0.8 truncated to integer error on compile . This is my code

b := img.Bounds()

heightImg := b.Max.Y  // height of image in pixels
widthImg := b.Max.X   // width of image in pixels
const a = .80
height := int(heightImg * a) // reduce height by 20%
width := int(widthImg * a)  // reduce width by 20%

 // resize image below which take in type int, int in the 2nd & 3rd parameter
new_img := imaging.Resize(img,width,height, imaging.Lanczos)

I am new to golang but this code right here gives me the error

    height := int(heightImg * a) 
    width := int(widthImg * a)

any suggestions would be great

like image 991
Rome Torres Avatar asked May 03 '17 19:05

Rome Torres


People also ask

Can you multiply a float and an integer?

The result of the multiplication of a float and an int is a float . Besides that, it will get promoted to double when passing to printf . You need a %a , %e , %f or %g format. The %d format is used to print int types.

How do you multiply in go?

Multiplication and DivisionThe sign we'll use in Go for multiplication is * and the sign we'll use for division is / . In Go, division has different characteristics depending on the numeric type we're dividing.

Can I multiply double with float?

if you multiply double with float variable the result will be double and you won't loose accuracy. However it depends on where the result is saved, if it's saved into a float variable then accuracy is lost.

Can you multiply a float?

First off, you can multiply floats. The problem you have is not the multiplication itself, but the original number you've used. Multiplication can lose some precision, but here the original number you've multiplied started with lost precision. This is actually an expected behavior.


1 Answers

If you want to multiply floats, you need to convert the number to a float:

height := int(float64(heightImg) * a) 
width := int(float64(widthImg) * a)
like image 92
JimB Avatar answered Oct 19 '22 19:10

JimB