ENH: support float format
brentp opened this issue · comments
Brent Pedersen commented
Given something like:
let ctx = newContext()
ctx["name"] = 1.234903242343234534
echo ctx["name"].castStr
I'd like to be able to specify to only output, for example 1.235
. I tried this:
proc `$`*(f:float): string =
return &"{f:.2f}"
but that didn't change the template output for me.
Pietro Peterlongo commented
one option could be to have a ctx["name_raw"]
which contains the float value and a ctx["name"]
that contains a lambda that formats ctx["name_raw"]
as a string and in the way you want it.
Ju commented
@brentp Nim-mustache does not process $
output.
You can wrap up your float values into a customized type and control the strformat leveraging by the castValue
API like below:
# File: issue_16.nim
import mustache, strformat
type HumanReadableFloat = object
vFloat*: float
proc castValue(value: HumanReadableFloat): Value =
Value(kind: vkString, vString: &"{value.vFloat:.2f}")
var c = newContext()
c["raw_float"] = 1.234903242343234534
c["readable_float"] = HumanReadableFloat(vFloat: 1.234903242343234534)
let s = """
{{ raw_float }}
{{ readable_float }}
"""
echo(s.render(c))
Output:
1.234903242343234
1.23
Brent Pedersen commented
cheers. I'll do that. thank you.