Category talk:Wren-fmt: Difference between revisions

→‎Source code: Bug fix plus new method group.
(Copied over source code from previous 'fmt' module talk page.)
 
(→‎Source code: Bug fix plus new method group.)
Line 252:
// Embeds a string or value 'v' in double quotes.
static q(v) { "\"%(v)\"" }
// Pads a number 'n' with leading spaces to a minimum width 'w' and a precision of 'p' decimal places.
// Precision is restricted to 14 places though entering a higher figure is not an error.
// Numbers are rounded and/or decimal places are zero-filled where necessary.
// Numbers which can't be expressed exactly use their default representation.
Line 262 ⟶ 263:
if (!p.isInteger || p < 0) Fiber.abort("Precision must be a non-negative integer")
if (n.abs > Conv.maxSafeInt || n.isInfinity || n.isNan) return s(w, n) // use 'normal' representation
var i =if (p ==> 014) ?p n.round= :14
var i = (np >== 0) ? n.floorround : n.ceiltruncate
var ns = "%(Conv.dec(i))"
if (i == 0 && n < 0) ns = "-" + ns
if (n.isInteger || p == 0) {
if (p > 0) return s(w, ns + "." + "0" * p)
Line 271 ⟶ 273:
var d = (n - i).abs
var pw = 10.pow(p)
d = (d * pw).round / pw
if (d == 0) return s(w, ns + "." + "0" * p)
var ds = "%(d)"[2..-1]
var c = ds.count
if (c < p) ds = ds + "0" * (p - c) + ds
return s(w, ns + "." + ds[0...p])
}
 
// Works like 'f' except replaces any trailing zeros after the decimal point with spaces.
// If the resulting string would end with a decimal point, a zero is first added back.
static g(w, n, p) {
var f = f(w, n, p)
if (f.contains(".") && f[-1] == "0") {
var l1 = f.count
f = f.trimEnd("0")
if (f[-1] == ".") f = f + "0"
f = f + (" " * (l1 - f.count))
}
return f
}
 
// As above but pads with leading zeros instead of spaces.
// Any minus sign will be placed before the padding.
// When used with negative 'w' behaves the same as the above methodmethods.
static fz(w, n, p) { (w >= 0) ? zfill(w, f(w, n, p).trimStart()) : f(w, n, p) }
static gz(w, n, p) { (w >= 0) ? zfill(w, g(w, n, p).trimStart()) : g(w, n, p) }
 
// Convenience versions of the above methods which use the default precision.
static f(w, n) { f(w, n, precision) }
static g(w, n) { g(w, n, precision) }
static fz(w, n) { fz(w, n, precision) }
static gz(w, n) { gz(w, n, precision) }
}
9,476

edits