Skip to content

Commit

Permalink
fix(rounding): check if the value is a float
Browse files Browse the repository at this point in the history
check the value is a float and if it is, convert it to a float
then convert back to a string by rounding off the significant
zeros to the expected amount.

+ref: #55
  • Loading branch information
KingMichaelPark committed Jun 1, 2024
1 parent 63eb307 commit 567249e
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 2 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*.out
c.out
coverage.html
.mise.toml

# Test binary, built with `go test -c`
*.test
Expand Down Expand Up @@ -43,4 +44,4 @@ test/test
.DS_Store

# Editor files
.idea
.idea
46 changes: 46 additions & 0 deletions rounding_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package xlsxreader

import (
"testing"

"github.com/stretchr/testify/require"
)

func getColCount(f *XlsxFileCloser) int {
row := <-f.ReadRows(f.Sheets[0])
if row.Error != nil {
return 0
}
return asIndex(row.Cells[len(row.Cells)-1].Column) + 1
}

func TestFloatingPointRounding(t *testing.T) {

t.Run("rounding", func(t *testing.T) {
xl, err := OpenFile("./test/test-rounding.xlsx")
// Create an instance of the reader by opening a target file
var target string
// Ensure the file reader is closed once utilised
defer xl.Close()
numColumns := getColCount(xl)
for row := range xl.ReadRows(xl.Sheets[0]) {
if row.Error != nil {
continue
}
csvRow := make([]string, numColumns)
for _, curCell := range row.Cells {
colIndex := asIndex(curCell.Column)
if curCell.Column == "L" && curCell.Row == 2 {
target = curCell.Value
}
if colIndex < numColumns {
csvRow[colIndex] = curCell.Value
}
}

}

require.NoError(t, err)
require.Equal(t, "4.4", target)
})
}
7 changes: 6 additions & 1 deletion rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,12 @@ func (x *XlsxFile) getCellValue(r rawCell) (string, error) {
return formattedDate, nil
}

return *r.Value, nil
v, err := strconv.ParseFloat(*r.Value, 64)
if err != nil {
return *r.Value, nil
}
new_val := strconv.FormatFloat(v, 'f', -1, 64)
return new_val, nil
}

func (x *XlsxFile) getCellType(r rawCell) CellType {
Expand Down
Binary file added test/test-rounding.xlsx
Binary file not shown.

0 comments on commit 567249e

Please sign in to comment.