Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

C# Formatting integers

I have an integer which I want to convert to a string, but taking the last 3 numbers and showing only the first 2 of them as decimals,

something like this: 85893 => 85.89 or failing that: 469 => 0.46

I have thought about rounding it, formatting it with string, even regex, but I would like to know what is the most optimal way to do it, since it will be done in several iterations per second

[UPDATE] The best performing option I found was: @juharr

(num / 1000M).ToString("F2");

thanks a lot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It would appear your are truncating towards zero rather than rounding to get to 1/100ths.

I might do something like this:

public static string FormatSpecial( this int n )
{
  return Math.Round( ((decimal) n) / 1000 , 2 , MidpointRounding.ToZero ).ToString();
}

If that is insufficiently efficient, perhaps something like this:

public static string FormatSpecial( this int n )
{
  int ddd = n         / 1000 ; // integer portion
  int ttt = n         % 1000 ; // fractional portion (1/1000ths)
  int hh  = thousands /   10 ; // truncate thousandths to 1/100ths

  string s = string.Format("{0}.{1:00}", ddd, hh );
}

Just 3 integer divisions, followed by conversion to string.

I would hope that the optimizer and the JIT would collapse the 1st 2 divisions into a single machine instruction: on most CPUs, the integer division op usually produces both a quotient and remainder as its result.

If that's still insufficiently efficient, then something like this to optimize the string formatting. Since we know that the max value of a 64-bit unsigned integer (ulong) is 18446744073709551615, the resulting formatted string will never exceed 25 characters in length. So...

public static string FormatSpecial( this int n )
{
  const  BUFL          = 25             ;
  const  DECIMAL_POINT = BUFL - 4       ;
  const  MIN           = BUFL - 5       ;
  char[] buf           = new char[BUFL] ;
  int    i             = BUFL - 1       ;

  do
  {
    if ( i == DECIMAL_POINT)
    {
      buf[i--] = '.';
    }

    char digit = '0' + ( n % 10 );
    buf[i--] = digit ;

    n /= 10 ;

  } while ( n != 0 || i > MIN );

  int len = BUFL - i - 1;
  return new String( buf , i , len );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...