DEV Community

Discussion on: Daily Challenge #49 - Dollars and Cents

Collapse
 
dak425 profile image
Donald Feury • Edited

Go - with tests as usual

fun fact - this was the first time I wrote anything using Vim

dollars.go

package dollars

import (
    "fmt"
)

// Dollars returns the string representation of a float as a dollar amount
func Dollars(amount float64) string {
    return fmt.Sprintf("$%.2f", amount)
}

dollars_test.go

package dollars

import (
    "testing"
)

var testCases = []struct {
    description string
    input       float64
    expected    string
}{
    {
        "only cents",
        .04,
        "$0.04",
    },
    {
        "only dollars",
        3,
        "$3.00",
    },
    {
        "cents & dollars",
        3.14,
        "$3.14",
    },
    {
        "amounts with more than two decimal places round to the nearest cent",
        4.478,
        "$4.48",
    },

}

func TestDollars(t *testing.T) {
    for _, test := range testCases {
        if result := Dollars(test.input); result != test.expected {
            t.Fatalf("FAILED: %s - Dollars(%f): %s, expected %s \n", test.description, test.input, result, test.expected)
        }
        t.Logf("PASS: %s \n", test.description)
    }
}

Collapse
 
tiash990 profile image
Tiash

I'm not sure, but I think that "Sprintf" rounds to nearest integer.
Try with a value like 3.149 if still returns 3.14 or 3.15

Collapse
 
dak425 profile image
Donald Feury

Added additional test case to clarify current rounding behavior.

Collapse
 
dak425 profile image
Donald Feury • Edited

Yeah it rounds to the nearest cent in this case, the question becomes then do we want it to work that way, or do we say "Hey you don't have a full cent" so it always rounds down?