Skip to content

How to get a parseable unit string #412

@MartinOtter

Description

@MartinOtter

I have the following problem:

using Unitful
# Variable with unit defined
v = 2.0u"m/s"    

# Extract unit as string
v_unit = string(unit(v))   # = "m s^-1"

# This string cannot be parsed
uparse(v_unit)   # gives an error

# Therefore code generation with the v_unit string does not work
code = :( @u_str($v_unit) )      # = :( u"m s^-1" )
eval(code)   # Gives an error

The reason is that string(unit(v)) returns a string that cannot be parsed. In Julia this seems to be an unusual behavior because string(something) typically returns a string representation of something that can be again parsed by Julia.

I searched extensively in Unitful documentation and the Issues but did not find a solution.

I currently use a bad hack (that most likely does not work in all situations), by replacing " " by "*":

v_unit = replace(  string(unit(v)), " " => "*")    # = "m*s^-1"
uparse(v_unit)   # fine
code = :( @u_str($v_unit) )      # = :( u"m*s^-1" )
eval(code)   # fine

Help is appreciated

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions