decimal icon indicating copy to clipboard operation
decimal copied to clipboard

trim trailing 0s

Open zeitlinger opened this issue 5 years ago • 7 comments

Is there a way to trim trailing 0s like the following?

	s := d.String()
	if strings.Contains(s, ".") {
		s = strings.TrimRight(strings.TrimRight(s, "0"), ".")
	}

Is there a way to format a number with a given number of digits after the "." - something easier than this

	str := fmt.Sprintf("%f", d)
	i := strings.Index(strings.TrimLeft(str, "-"), ".")
	if i < 0 {
		i = len(str)
	}

	r := p.Round(i + int(precision))

	format := "%." + strconv.Itoa(int(precision)) + "f%%"
	return fmt.Sprintf(format, r)

zeitlinger avatar Apr 27 '20 15:04 zeitlinger

Maybe you could copy some code from my formatter: https://github.com/bojanz/currency/blob/master/formatter.go

bojanz avatar May 15 '20 13:05 bojanz

Maybe you could copy some code from my formatter: https://github.com/bojanz/currency/blob/master/formatter.go

I'm afraid I don't understand it.

What I'm trying to say:

  1. I have a working solution for both problems - which I included in the description
  2. I'm wondering if the library already supports it - and I just didn't understand it

zeitlinger avatar May 15 '20 13:05 zeitlinger

Apologies, I read your issue in a hurry and thought you were looking for a better formatting helper.

bojanz avatar May 15 '20 14:05 bojanz

Just for string formatting? You can use the width verbs. Quantize does what you want too, but modifies the receiver.

ericlagergren avatar May 16 '20 03:05 ericlagergren

ah, this is for the second use case - and works sometimes, but not always

func TestAsPercentageWithPrecision(t *testing.T) {
	assert.Equal(t, "100.00", withPrecision("99.999999", 2)) //fails because it's "100.0"
}

func withPrecision(s string, precision uint) string {
	f := parse(s)
	return fmt.Sprintf("%s", f.Quantize(int(precision)))
}

func parse(s string) *decimal.Big {
	p, _ := new(decimal.Big).SetString(s)
	return p
}

zeitlinger avatar May 18 '20 11:05 zeitlinger

@zeitlinger Call Quantize twice as a workaround, this will lead to 100.00 (and also works if precision is 0)

Looking at the date of this issue... Is this library still supported, or "kind of archived"?

lotodore avatar Sep 28 '22 13:09 lotodore

@lotodore I just haven't had a lot of time to work on it lately. But I will always make time to review and accept PRs.

ericlagergren avatar Oct 06 '22 19:10 ericlagergren