Stringify number with unicode minus symbol

This is a minor, simple question. Is there already a function that acts like string() but uses the unicode minus symbol for negative numbers? (It would be nice if string() accepted such an option.)

If not, I’d just write a one-line function like this

num2str(a) =  (a >= 0) ? string(a) : "−" * string(-a)

I need this for annotations in plots.

how about

julia> num2str(a) = replace(string(a), '-' => '−')
num2str (generic function with 1 method)

julia> num2str(-2)
"−2"

possibly r"^-" => '−' if you want to ensure it’s the first character (though I can’t think of a case where this would matter).

Alternative in the vein of your function:

n2s(a) = "$('−'^(a < 0))$(abs(a))"
1 Like

I cannot see the difference in Plots.jl gr backend, between the two minus characters.
Need to use LaTeXStrings to see the difference:

using Plots, LaTeXStrings
num2str(a) = replace(string(a), '-' => L"−")
x = y = -7:7
plot(x,y, formatter = num2str)
2 Likes

The difference depends on the font.

Here’s a scrappy diagram that’s mostly correct (fonts sometimes don’t want to play nicely):

1 Like

I cannot see the difference in Plots.jl gr backend

On my system (julia 1.8.5 on macOS 13.1), I got the image at the bottom of this message from the code below. The difference between the hyphen and unicode minus is clear. Note that the numeric labels on the y axis (likely) uses the unicode minus symbol.

using Plots
m=-7
a = rand(Float64, 10) .- 0.5
plot(a;ylim=(-0.5,0.5))
annotate!(3,  0.1, "m=$(m)")
annotate!(3, -0.1, "m=−7")

1 Like

possibly r"^-" => ‘−’ if you want to ensure it’s the first character

This comment of yours has made me realize that your first approach is better because of complex numbers:

c = 1 - 2im
plot( . . . )
annotate!(x, y, "c=$(c)") # uses hyphen
annotate!(x, y, "c=$(num2str(c))") # uses unicode minus

My sample code in my original post doesn’t work for complex numbers!

1 Like