-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcformat.jl
More file actions
338 lines (315 loc) · 12.3 KB
/
Copy pathcformat.jl
File metadata and controls
338 lines (315 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
include("printf.jl")
const _formatters = Dict{ASCIIStr,FmtSpec}()
function _get_formatter(fmt)
global _formatters
chkfmt = get(_formatters, fmt, nothing)
chkfmt === nothing || return chkfmt
_formatters[fmt] = FmtSpec(fmt)
end
_cfmt_comma(fspec::FmtSpec, x) = addcommasreal(_cfmt(fspec, x), Char(fspec.tsep))
_cfmt_comma(fspec::FmtSpec{FmtStr}, x::Rational) = addcommasrat(_cfmt(fspec, x), Char(fspec.tsep))
_cfmt_comma(fspec::FmtSpec{<:FmtInts}, x) = checkcommas(_cfmt(fspec, x), Char(fspec.tsep))
function _cfmt(fspec::FmtSpec, x)
sv = Base.StringVector(23) # Trust that lower level code will expand if necessary
pos = _fmt(sv, 1, fspec, x)
resize!(sv, pos - 1)
String(sv)
end
cfmt(fspec::FmtSpec, x) = fspec.tsep == 0 ? _cfmt(fspec, x) : _cfmt_comma(fspec, x)
cfmt(fmtstr::ASCIIStr, x) = cfmt(_get_formatter(fmtstr), x)
function generate_formatter(fmt::ASCIIStr)
fspec = _get_formatter(fmt)
fspec.tsep == 0 ? x -> _cfmt(fspec, x) : x -> _cfmt_comma(fspec, x)
end
function addcommasreal(s, sep)
len = length(s)
dpos = findfirst( isequal('.'), s )
dpos !== nothing && return addcommas(s, len, dpos-1, sep)
# find the rightmost digit
for i in len:-1:1
isdigit( s[i] ) && return addcommas(s, len, i, sep)
end
s
end
# commas are added to only the numerator
addcommasrat(s, sep) = addcommas(s, length(s), findfirst( isequal('/'), s )-1, sep)
function checkcommas(s, sep)
len = length(s)
for i in len:-1:1
isdigit( s[i] ) && return addcommas(s, len, i, sep)
end
s
end
function addcommas(s::T, len, lst, sep) where {T<:AbstractString}
lst < 4 && return s
beg = 1
while beg < len
isdigit(s[beg]) && break
beg += 1
end
dig = lst - beg + 1
dig < 4 && return s
commas = div(dig - 1, 3)
sv = Base.StringVector(len + commas)
for i = 1:beg-1; sv[i] = s[i]; end
cnt = dig - commas*3
pos = beg - 1
for i = beg:lst-3
sv[pos += 1] = s[i]
(cnt -= 1) == 0 && (cnt = 3; sv[pos += 1] = sep)
end
for i = lst-2:len; sv[i+commas] = s[i]; end
T(sv)
end
addcommas(s, sep) = (l = length(s); addcommas(s, l, l, sep))
function generate_format_string(;
width::Int=-1,
precision::Int= -1,
leftjustified::Bool=false,
zeropadding::Bool=false,
commas::Bool=false,
signed::Bool=false,
positivespace::Bool=false,
alternative::Bool=false,
conversion::ASCIIStr="f" #aAdecEfFiosxX
)
s = ['%'%UInt8]
commas &&
push!(s, '\'')
alternative && in( conversion[1], "aAeEfFoxX" ) &&
push!(s, '#')
zeropadding && !leftjustified && width != -1 &&
push!(s, '0')
if signed
push!(s, '+')
elseif positivespace
push!(s, ' ')
end
if width != -1
leftjustified && push!(s, '-')
append!(s, _codeunits(string( width )))
end
precision != -1 &&
append!(s, _codeunits(string( '.', precision )))
String(append!(s, _codeunits(conversion)))
end
"""
Format a value, using the following keyword arguments to control formatting
(Bold keywords are not printf standard):
* width. Integer. Try to fit the output into this many characters. May not be successful.
Sacrifice space first, then commas.
* precision. Integer. How many decimal places.
* leftjustified. Boolean
* zeropadding. Boolean
* commas. Boolean. Thousands-group separator.
* signed. Boolean. Always show +/- sign?
* positivespace. Boolean. Prepend an extra space for positive numbers? (so they align nicely with negative numbers)
* **parens**. Boolean. Use parenthesis instead of "-". e.g. `(1.01)` instead of `-1.01`. Useful in finance. Note that
you cannot use `signed` and `parens` option at the same time.
* **stripzeros**. Boolean. Strip trailing '0' to the right of the decimal (and to the left of 'e', if any ).
* It may strip the decimal point itself if all trailing places are zeros.
* This is true by default if precision is not given, and vice versa.
* alternative. Boolean. See `#` alternative form explanation in standard printf documentation
* conversion. length=1 string. Default is type dependent. It can be one of `aAeEfFoxX`. See standard
printf documentation.
* **mixedfraction**. Boolean. If the number is rational, format it in mixed fraction e.g. `1_1/2` instead of `3/2`
* **mixedfractionsep**. Default `_`
* **fractionsep**. Default `/`
* **fractionwidth**. Integer. Try to pad zeros to the numerator until the fractional part has this width
* **tryden**. Integer. Try to use this denominator instead of a smaller one. No-op if it'd lose precision.
* **suffix**. String. This strings will be appended to the output. Useful for units/%
* **autoscale**. Symbol, default `:none`. It could be `:metric`, `:binary`, or `:finance`.
* `:metric` implements common SI symbols for large and small numbers e.g. `M`, `k`, `μ`, `n`
* `:binary` implements common ISQ symbols for large numbers e.g. `Ti`, `Gi`, `Mi`, `Ki`
* `:finance` implements common finance/news symbols for large numbers e.g. `b` (billion), `m` (millions)
"""
function format( x::T;
width::Int=-1,
precision::Int= -1,
leftjustified::Bool=false,
zeropadding::Bool=false, # when right-justified, use 0 instead of space to fill
commas::Bool=false,
signed::Bool=false, # +/- prefix
positivespace::Bool=false,
stripzeros::Bool=(precision== -1),
parens::Bool=false, # use (1.00) instead of -1.00. Used in finance
alternative::Bool=false, # usually for hex
mixedfraction::Bool=false,
mixedfractionsep::UTF8Str="_",
fractionsep::UTF8Str="/", # num / den
fractionwidth::Int = 0,
tryden::Int = 0, # if 2 or higher,
# try to use this denominator, without losing precision
suffix::UTF8Str="", # useful for units/%
autoscale::Symbol=:none, # :metric, :binary or :finance
conversion::ASCIIStr=""
) where {T<:Real}
checkwidth = commas
if conversion == ""
if T <: AbstractFloat || T <: Rational && precision != -1
actualconv = "f"
elseif T <: Unsigned
actualconv = "x"
elseif T <: Integer
actualconv = "d"
else
conversion = "s"
actualconv = "s"
end
else
actualconv = conversion
end
signed && commas && error( "You cannot use signed (+/-) AND commas at the same time")
T <: Rational && conversion == "s" && (stripzeros = false)
if ( T <: AbstractFloat && actualconv == "f" || T <: Integer ) && autoscale != :none
actualconv = "f"
if autoscale == :metric
scales = [
(1e24, "Y" ),
(1e21, "Z" ),
(1e18, "E" ),
(1e15, "P" ),
(1e12, "T" ),
(1e9, "G"),
(1e6, "M"),
(1e3, "k") ]
if abs(x) > 1
for (mag, sym) in scales
if abs(x) >= mag
x /= mag
suffix = string(sym, suffix)
break
end
end
elseif T <: AbstractFloat
smallscales = [
( 1e-24, "y" ),
( 1e-21, "z" ),
( 1e-18, "a" ),
( 1e-15, "f" ),
( 1e-12, "p" ),
( 1e-9, "n" ),
( 1e-6, "μ" ),
( 1e-3, "m" ) ]
for (mag,sym) in smallscales
if abs(x) < mag*1000
x /= mag
suffix = string(sym, suffix)
break
end
end
end
else
if autoscale == :binary
scales = [
(1024.0 ^8, "Yi" ),
(1024.0 ^7, "Zi" ),
(1024.0 ^6, "Ei" ),
(1024.0 ^5, "Pi" ),
(1024.0 ^4, "Ti" ),
(1024.0 ^3, "Gi"),
(1024.0 ^2, "Mi"),
(1024.0, "Ki")
]
else # :finance
scales = [
(1e12, "t" ),
(1e9, "b"),
(1e6, "m"),
(1e3, "k") ]
end
for (mag, sym) in scales
if abs(x) >= mag
x /= mag
suffix = string(sym, suffix)
break
end
end
end
end
nonneg = x >= 0
fractional = 0
if T <: Rational && mixedfraction
actualconv = "d"
actualx = trunc( Int, x )
fractional = abs(x) - abs(actualx)
else
actualx = (parens && !in( actualconv[1], "xX" )) ? abs(x) : x
end
s = cfmt( generate_format_string( width=width,
precision=precision,
leftjustified=leftjustified,
zeropadding=zeropadding,
commas=commas,
signed=signed,
positivespace=positivespace,
alternative=alternative,
conversion=actualconv
),
actualx)
if T <:Rational && conversion == "s"
if mixedfraction && fractional != 0
num = fractional.num
den = fractional.den
if tryden >= 2 && mod( tryden, den ) == 0
num *= div(tryden,den)
den = tryden
end
fs = string( num, fractionsep, den)
length(fs) < fractionwidth &&
(fs = string(repeat( "0", fractionwidth - length(fs) ), fs))
s = (actualx != 0
? string(rstrip(s), mixedfractionsep, fs)
: (nonneg ? fs : string('-', fs)))
checkwidth = true
elseif !mixedfraction
s = replace( s, "//" => fractionsep )
checkwidth = true
end
elseif stripzeros && in( actualconv[1], "fFeEs" )
dpos = findfirst( isequal('.'), s )
dpos === nothing && (dpos = length(s))
if actualconv[1] in "eEs"
epos = findfirst(isequal(actualconv[1] == 'E' ? 'E' : 'e'), s)
rpos = (epos === nothing) ? length( s ) : (epos-1)
else
rpos = length(s)
end
# rpos at this point is the rightmost possible char to start
# stripping
stripfrom = rpos+1
for i = rpos:-1:dpos+1
if s[i] == '0'
stripfrom = i
elseif s[i] ==' '
continue
else
break
end
end
if stripfrom <= rpos
# everything after decimal is 0, so strip the decimal too
s = string(s[1:stripfrom-1-(stripfrom == dpos+1)], s[rpos+1:end])
checkwidth = true
end
end
s = string(s, suffix)
if parens && !in( actualconv[1], "xX" )
# if zero or positive, we still need 1 white space on the right
s = nonneg ? string(' ', strip(s), ' ') : string('(', strip(s), ')')
checkwidth = true
end
if checkwidth && width != -1
if (len = length(s) - width) > 0
s = replace( s, " " => ""; count=len )
if (len = length(s) - width) > 0
endswith(s, " ") && (s = reverse(replace(reverse(s), " " => ""; count=len)))
(len = length(s) - width) > 0 && (s = replace( s, "," => ""; count=len ))
end
elseif len < 0
# Todo: should use lpad or rpad here, can be more efficient
s = leftjustified ? string(s, repeat( " ", -len )) : string(repeat( " ", -len), s)
end
end
s
end