glue icon indicating copy to clipboard operation
glue copied to clipboard

Automatically format doubles

Open hadley opened this issue 6 years ago • 3 comments

glue::glue("{1/3}")
#> 0.333333333333333

Would be nice if you got something with fewer digits (maybe respecting getOptions("digits"))?

hadley avatar Apr 09 '18 17:04 hadley

This happens because glue essentially does this right now

as.character(eval(parse(text = "1/3")))
#> [1] "0.333333333333333"

I could have glue call format() instead of as.character()

format(eval(parse(text = "1/3")))
#> [1] "0.3333333"

Which would help in that case, but would cause other issues in other cases, e.g.

format(eval(parse(text = "c(1, 100, 1000)")))
#> [1] "   1" " 100" "1000"

Not sure what a good solution is, format() seems problematic though as it adds whitespace even with character input.

format(eval(parse(text = "as.character(c(1, 100, 1000))")))
#> [1] "1   " "100 " "1000"

jimhester avatar Apr 09 '18 20:04 jimhester

What if you just called the new format wrapper when !is.object(x) && is.double(x) ?

hadley avatar Apr 09 '18 22:04 hadley

One alternative would be to call format(trim = TRUE, justify = "none") which should turn off padding in all cases.

format(c(1, 10, 100, 1000), trim = TRUE, justify = "none")
#> [1] "1"    "10"   "100"  "1000"
format(as.character(c(1, 10, 100, 1000)), trim = TRUE, justify = "none")
#> [1] "1"    "10"   "100"  "1000"

But that also has unfortunate behavior (see below) so maybe we do need something like #87

format(c(1/3, 1, 10, 100, 1000), trim = TRUE, justify = "none")
#> [1] "0.3333333"    "1.0000000"    "10.0000000"   "100.0000000"  "1000.0000000"

jimhester avatar Apr 11 '18 12:04 jimhester

I haven't needed this in the last 5 years, so lets say it's not worth implementing 😄

hadley avatar Jan 26 '23 23:01 hadley