Browse Source

Optimize the output number for small float.

Hugh Gao 10 years ago
parent
commit
707568c5c2
2 changed files with 20 additions and 3 deletions
  1. 7 2
      cell.go
  2. 13 1
      cell_test.go

+ 7 - 2
cell.go

@@ -70,7 +70,7 @@ func (c *Cell) String() string {
 
 // SetFloat sets the value of a cell to a float.
 func (c *Cell) SetFloat(n float64) {
-	c.SetFloatWithFormat(n, "0.00e+00")
+	c.SetFloatWithFormat(n, "general")
 }
 
 /*
@@ -88,7 +88,12 @@ func (c *Cell) SetFloat(n float64) {
 // SetFloatWithFormat sets the value of a cell to a float and applies
 // formatting to the cell.
 func (c *Cell) SetFloatWithFormat(n float64, format string) {
-	c.Value = strconv.FormatFloat(n, 'e', -1, 64)
+	// beauty the output when the float is small enough
+	if n != 0 && n < 0.00001 {
+		c.Value = strconv.FormatFloat(n, 'e', -1, 64)
+	} else {
+		c.Value = strconv.FormatFloat(n, 'f', -1, 64)
+	}
 	c.numFmt = format
 	c.formula = ""
 	c.cellType = CellTypeNumeric

+ 13 - 1
cell_test.go

@@ -97,11 +97,23 @@ func (s *CellSuite) TestGetStyleWithBorders(c *C) {
 func (l *CellSuite) TestSetFloatWithFormat(c *C) {
 	cell := Cell{}
 	cell.SetFloatWithFormat(37947.75334343, "yyyy/mm/dd")
-	c.Assert(cell.Value, Equals, "3.794775334343e+04")
+	c.Assert(cell.Value, Equals, "37947.75334343")
 	c.Assert(cell.numFmt, Equals, "yyyy/mm/dd")
 	c.Assert(cell.Type(), Equals, CellTypeNumeric)
 }
 
+func (l *CellSuite) TestSetFloat(c *C) {
+	cell := Cell{}
+	cell.SetFloat(0)
+	c.Assert(cell.Value, Equals, "0")
+	cell.SetFloat(0.000005)
+	c.Assert(cell.Value, Equals, "5e-06")
+	cell.SetFloat(100.0)
+	c.Assert(cell.Value, Equals, "100")
+	cell.SetFloat(37947.75334343)
+	c.Assert(cell.Value, Equals, "37947.75334343")
+}
+
 // We can return a string representation of the formatted data
 func (l *CellSuite) TestFormattedValue(c *C) {
 	cell := Cell{Value: "37947.7500001"}