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 );
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…