Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: support float format #16

Closed
brentp opened this issue Jun 9, 2021 · 4 comments
Closed

ENH: support float format #16

brentp opened this issue Jun 9, 2021 · 4 comments
Labels
question Further information is requested

Comments

@brentp
Copy link

brentp commented Jun 9, 2021

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.

@pietroppeter
Copy link
Sponsor Contributor

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.

@soasme
Copy link
Owner

soasme commented Jun 10, 2021

@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

@soasme
Copy link
Owner

soasme commented Jun 10, 2021

Please see how to use castValue doc here.

@soasme soasme added the question Further information is requested label Jun 10, 2021
@brentp
Copy link
Author

brentp commented Jun 10, 2021

cheers. I'll do that. thank you.

@brentp brentp closed this as completed Jun 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants