Skip to content

Commit

Permalink
Fixes #286 - Add leading/trailing 0 to Float32 literals (#287)
Browse files Browse the repository at this point in the history
* fix #286

Add leading/trailing 0 for Float32 literals, similar to how we do it for
other Float literals

* fmt

* doc
  • Loading branch information
domluna authored Sep 7, 2020
1 parent 878fda1 commit ba44cee
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 5 deletions.
10 changes: 10 additions & 0 deletions docs/src/transforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ a = .1
a = 0.1
```

For `Float32` if there is no decimal point, `.0` is added:

```julia
a = 1f0

->

a = 1.0f0
```

See [this issue](https://github.com/domluna/JuliaFormatter.jl/issues/66) for more details.

## Surround `where` arguments with curly brackets
Expand Down
26 changes: 21 additions & 5 deletions src/styles/default/pretty.jl
Original file line number Diff line number Diff line change
Expand Up @@ -366,12 +366,28 @@ end
loc = cursor_loc(s)
if !is_str_or_cmd(cst.kind)
val = cst.val
if cst.kind === Tokens.FLOAT && cst.val[end] == '.'
# If a floating point ends in `.`, add trailing zero.
val *= '0'
elseif cst.kind === Tokens.FLOAT && cst.val[1] == '.'
val = '0' * val

if cst.kind === Tokens.FLOAT && endswith(cst.val, "f0")
# Float32
val = val[1:end-2]
dotidx = findlast(c -> c == '.', val)
if dotidx === nothing
val *= ".0"
elseif dotidx == length(val)
val *= '0'
elseif dotidx == 1
val = '0' * val
end
val *= "f0"
elseif cst.kind === Tokens.FLOAT
if endswith(cst.val, ".")
# If a floating point ends in `.`, add trailing zero.
val *= '0'
elseif startswith(cst.val, ".")
val = '0' * val
end
end

s.offset += cst.fullspan
return FST(cst, loc[1], loc[1], val)
end
Expand Down
20 changes: 20 additions & 0 deletions test/issues.jl
Original file line number Diff line number Diff line change
Expand Up @@ -568,4 +568,24 @@
@test fmt(str_) == str
@test fmt(str, whitespace_ops_in_indices = true) == str_
end

@testset "issue 286 - Float32 leading/trailing zeros" begin
str_ = """
a = 3.f0
b = 3f0
c = 30f0
d = 30.0f0
e = 30.123f0
f = .123f0
"""
str = """
a = 3.0f0
b = 3.0f0
c = 30.0f0
d = 30.0f0
e = 30.123f0
f = 0.123f0
"""
@test fmt(str_) == str
end
end

0 comments on commit ba44cee

Please sign in to comment.