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

Add Writer::SetMaxDecimalPlaces() #536

Merged
merged 1 commit into from
Feb 15, 2016
Merged

Add Writer::SetMaxDecimalPlaces() #536

merged 1 commit into from
Feb 15, 2016

Conversation

miloyip
Copy link
Collaborator

@miloyip miloyip commented Feb 11, 2016

Fixes #362

@miloyip miloyip mentioned this pull request Feb 11, 2016
miloyip added a commit that referenced this pull request Feb 15, 2016
Add Writer::SetMaxDecimalPlaces()
@miloyip miloyip merged commit 9ecf073 into master Feb 15, 2016
@DavidRJohns
Copy link

Great new feature. Great library in general! Is there a way to add the ability for it to round as opposed to truncating? I tried to read through the paper with the Grisu2 algorithm and saw that the paper also has a Grisu2b algorithm that rounds. Is there a way to modify dtoa to use this rounding algorithm? Maybe both algoritms could be implemented and a class member could be added to distinguish between rounding or truncating.

@miloyip miloyip deleted the issue362 branch June 20, 2017 08:37
@jdemeyer
Copy link

+1 to the comment of @DavidRJohns

Unfortunately, the current implementation is lossy: reading a floating point number with a given number of decimal places and then writing that number back with the same number of decimal places can result in a different number being written. Example: reading 50.907667 and writing it back with 6 decimal places gives 50.907666.

@Llerd
Copy link

Llerd commented Sep 1, 2024

I needed rounding rather than truncating, so I added this block in the initial part of Prettify function. Use as you see fit.

inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) {
  int kk = length + k;  // 10^(kk-1) <= v < 10^kk

  if (kk > -6 && kk <= 21) {
    // 29.9995xxx -> 30.000
    int rounder =  kk + maxDecimalPlaces;
    if (length > rounder && buffer[rounder] >= '5') {
      for (int i = rounder - 1; i >= 0; i--) {
        buffer[i]++;
        if (buffer[i] <= '9')
          break;

        // overflow to next digit
        if (i != 0) {
          buffer[i] = '0';
        } else {
          // 9.9995xxx -> 10.000
          // Need to insert an initial '1', shift decimal and set rounder to 0
          buffer[0] = '1';
          buffer[rounder] = '0';
          kk++;
          k--;
        }
      }
    }
  }

Also, tested previous commenters 50.907667 value, but that seems fixed already.

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.

Truncate Double Values
5 participants