#Why does this math look like this?

9 messages · Page 1 of 1 (latest)

gilded kayak
#

Hi guys. Im learning go, and i just did something that i can't get. Could someone tell me why this float math returns some number like "860.9000000000001" ?

package main

import "fmt"

type CheckingAccount struct {
    owner        string
    agenceNumber int
    account      int
    ballance     float64
}

func (sender *CheckingAccount) Transfer(recipient *CheckingAccount, transferValue float64) bool {
    if transferValue > sender.ballance || transferValue <= 0 {
        return false
    }

    sender.ballance -= transferValue
    recipient.ballance += transferValue
    return true
}

func main() {
    account := CheckingAccount{
        owner:        "Antonio",
        agenceNumber: 0567,
        account:      123456,
        ballance:     1380.90,
    }

    account2 := CheckingAccount{
        "Antonio",
        0567,
        123456,
        1380.90,
    }

    fmt.Println(account, account2)
    account.Transfer(&account2, 520.)
    fmt.Println(account, account2)
}

output:

{Antonio 375 123456 1380.9} {Antonio 375 123456 1380.9}
{Antonio 375 123456 860.9000000000001} {Antonio 375 123456 1900.9}
orchid geyser
# gilded kayak Hi guys. Im learning go, and i just did something that i can't get. Could someon...

https://www.youtube.com/watch?v=Oo89kOv9pVk explains it in way too much detail

An introduction to the floating point numbers (iee-754), and some of the oddities surrounding it.

Support me on:
Patreon: https://www.patreon.com/simondevyt

Follow me on:
Twitter: https://twitter.com/iced_coffee_dev
Instagram: https://www.instagram.com/beer_and_code/
Github: https://github.com/simondevyoutube/

Some great resources:
https://d...

▶ Play video
#

slightly above absolutely no one uses floats for monetary computations, fixed point math is what is used

#

so you use uint or int but with a scalling factor

rustic radish
#

That's an inherant property of floating point numbers.

#

Never use floats when you want accuracy.

gilded kayak
#

did not know about that

#

appreciated guys !

verbal obsidian
#

Yeah I don’t know why a lot of coding examples use floats for money it’s a really bad idea