From 51229b9921b0afc9b33a3e0ef4f82774733d54f2 Mon Sep 17 00:00:00 2001 From: Christoph Mitterhofer Date: Thu, 9 Sep 2021 13:14:39 +0200 Subject: [PATCH] Fixed RTrim(floatstr, "0.") converts "10.0" to "1" --- cache_content_text.go | 15 ++++++++++++--- fontsizefloat64_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/cache_content_text.go b/cache_content_text.go index 3f65a27..d81772d 100644 --- a/cache_content_text.go +++ b/cache_content_text.go @@ -4,7 +4,8 @@ import ( "errors" "fmt" "io" - "strings" + "math" + "strconv" ) //ContentTypeCell cell @@ -111,6 +112,14 @@ func (c *cacheContentText) calX() (float64, error) { return 0.0, errors.New("contentType not found") } +// FormatFloatTrim converts a float64 into a string, like Sprintf("%.3f") +// but with trailing zeroes (and possibly ".") removed +func FormatFloatTrim(floatval float64) (formatted string) { + const precisionFactor = 1000.0 + roundedFontSize := math.Round(precisionFactor*floatval) / precisionFactor + return strconv.FormatFloat(roundedFontSize, 'f', -1, 64) +} + func (c *cacheContentText) write(w io.Writer, protection *PDFProtection) error { r := c.textColor.r g := c.textColor.g @@ -137,8 +146,8 @@ func (c *cacheContentText) write(w io.Writer, protection *PDFProtection) error { fmt.Fprintf(w, "%0.2f %0.2f TD\n", x, y) fmt.Fprintf(w, "/F%d %s Tf\n", c.fontCountIndex, - // remove trailing zeroes and comma. "12.000" => "12" - strings.TrimRight(fmt.Sprintf("%.3f", c.fontSize), "0.")) + FormatFloatTrim(c.fontSize)) + if c.txtColorMode == "color" { fmt.Fprintf(w, "%0.3f %0.3f %0.3f rg\n", float64(r)/255, float64(g)/255, float64(b)/255) } diff --git a/fontsizefloat64_test.go b/fontsizefloat64_test.go index 018cb72..654a898 100644 --- a/fontsizefloat64_test.go +++ b/fontsizefloat64_test.go @@ -1,6 +1,7 @@ package gopdf import ( + "fmt" "testing" ) @@ -106,5 +107,29 @@ func TestSetFontWithString(t *testing.T) { if err == nil { t.Errorf("SetFont(string) + AddText: Should have gotten an error!\n") } +} +func ExampleFormatFloatTrim() { + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.0)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.01)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.001)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.0001)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.00001)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.99999)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.9999)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.999)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.99)) + fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.9)) + // Output: /F1 10 Tf + // /F1 10 Tf + // /F1 10.01 Tf + // /F1 10.001 Tf + // /F1 10 Tf + // /F1 10 Tf + // /F1 10 Tf + // /F1 10 Tf + // /F1 9.999 Tf + // /F1 9.99 Tf + // /F1 9.9 Tf }