JuliaPhysics / JuliaPhysics/Unitful.jl

How to get a parseable unit string

Open
#412 13 comments 2 reactions 0 assignees View on GitHub
Dominant language
Julia
Stars
675
Forks
124
Avg merge
3h 38m
Merged PRs (30d)
1

Description

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

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by reproducing the issue with string(unit(v)), uparse, and the @u_str code-generation example shown in the report. Read the implementations or tests for unit stringification and parsing; done means a unit string produced from a unit value can be parsed and used in the demonstrated generated-code path without the replacement hack.

Written by the indexing model from the issue text.

Assessment

Tech stack
julia
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.