MCPcopy
hub / github.com/tdewolff/minify / Decimal

Function Decimal

common.go:105–208  ·  view source on GitHub ↗

Decimal minifies a given byte slice containing a decimal and removes superfluous characters. It differs from Number in that it does not parse exponents. It does not parse or output exponents. prec is the number of significant digits. When prec is zero it will keep all digits. Only digits after the d

(num []byte, prec int)

Source from the content-addressed store, hash-verified

103// Decimal minifies a given byte slice containing a decimal and removes superfluous characters. It differs from Number in that it does not parse exponents.
104// It does not parse or output exponents. prec is the number of significant digits. When prec is zero it will keep all digits. Only digits after the dot can be removed to reach the number of significant digits. Very large number may thus have more significant digits.
105func Decimal(num []byte, prec int) []byte {
106 if len(num) <= 1 {
107 return num
108 }
109
110 // omit first + and register mantissa start and end, whether it's negative and the exponent
111 neg := false
112 start := 0
113 dot := -1
114 end := len(num)
115 if 0 < end && (num[0] == '+' || num[0] == '-') {
116 if num[0] == '-' {
117 neg = true
118 }
119 start++
120 }
121 for i, c := range num[start:] {
122 if c == '.' {
123 dot = start + i
124 break
125 }
126 }
127 if dot == -1 {
128 dot = end
129 }
130
131 // trim leading zeros but leave at least one digit
132 for start < end-1 && num[start] == '0' {
133 start++
134 }
135 // trim trailing zeros
136 i := end - 1
137 for ; dot < i; i-- {
138 if num[i] != '0' {
139 end = i + 1
140 break
141 }
142 }
143 if i == dot {
144 end = dot
145 if start == end {
146 num[start] = '0'
147 return num[start : start+1]
148 }
149 } else if start == end-1 && num[start] == '0' {
150 return num[start:end]
151 }
152
153 // apply precision
154 if 0 < prec && dot <= start+prec {
155 precEnd := start + prec + 1 // include dot
156 if dot == start { // for numbers like .012
157 digit := start + 1
158 for digit < end && num[digit] == '0' {
159 digit++
160 }
161 precEnd = digit + prec
162 }

Callers 3

TestDecimalFunction · 0.85
TestDecimalTruncateFunction · 0.85
TestDecimalRandomFunction · 0.85

Calls 1

lenFunction · 0.85

Tested by 3

TestDecimalFunction · 0.68
TestDecimalTruncateFunction · 0.68
TestDecimalRandomFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…