Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change default float format #2644

Closed
wants to merge 1 commit into from
Closed

Conversation

mperham
Copy link
Contributor

@mperham mperham commented May 24, 2016

The current format is lossy in the extreme. This prints the Float as-is with 8 digits of precision.

float = Time.now.epoch_f
p float.to_json

str = String.new(22) do |buffer|
  LibC.snprintf(buffer, 22, "%.8f", float)
  len = LibC.strlen(buffer)
  {len, len}
end
p str

$ crystal tmp.cr
"1.46413e+09"
"1464131025.34958601"

Does the size 22 constant need to be adjusted?

The current format is lossy in the extreme.  This prints the Float as-is with 8 digits of precision.

```
float = Time.now.epoch_f
p float.to_json

str = String.new(22) do |buffer|
  LibC.snprintf(buffer, 22, "%.8f", float)
  len = LibC.strlen(buffer)
  {len, len}
end
p str
```

$ crystal tmp.cr 
"1.46413e+09"
"1464131025.34958601"

Does the size 22 constant need to be adjusted?
@jhass
Copy link
Member

jhass commented May 24, 2016

I wonder if we still need the LibC.snprintf call actually, given we got sprintf / String#% these days. Well, at the end of the day it calls LibC.snprintf too. Still, might be better to have only one call to it for when we replace it with a Crystal implementation?

Anyway, specs would be awesome :)

@mperham
Copy link
Contributor Author

mperham commented May 24, 2016

I don't have a Crystal development environment set up just yet so I can't submit any non-trivial patches. Closing this since it's half-baked.

@mperham mperham closed this May 24, 2016
@mperham mperham deleted the patch-1 branch May 24, 2016 23:20
@jhass
Copy link
Member

jhass commented May 24, 2016

Oh that's easy if you already have Crystal installed it should be matter of running make in the repo and using bin/crystal to run the compiler & standard library of the repo. make spec runs the full testsuite, bin/crystal spec/... a specific file. :)

@asterite
Copy link
Member

@mperham I wouldn't change the default Float#to_s. With your change:

puts 1.0 # => 1.00000000

Current behaviour:

# maybe it should be 1.0
puts 1.0 # => 1

There's a similar issue here (I don't know why it's closed): #2220 . Formatting floats is hard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants