@@ -76,36 +76,28 @@ public static string ToUserFriendlyBytesLabel(this long bytes)
7676 /// <returns>String representation of the formatted number</returns>
7777 public static string ToKiloFormat ( this int number )
7878 {
79- bool isNegative = number < 0 ;
80- if ( isNegative )
79+ // To avoid overflow (with Math.Abs()). 1 difference won't make a difference in the simplified format :)
80+ if ( number == int . MinValue )
8181 {
82- number * = - 1 ;
82+ number = - 1 * int . MaxValue ;
8383 }
8484
85- if ( number < 1000 )
85+ if ( Math . Abs ( number ) < 1000 )
8686 {
87- return ( isNegative ? "-" : "" ) + number . ToString ( ) ;
87+ return number . ToString ( ) ;
8888 }
8989
9090 var powers = new [ ]
9191 {
92- new { Pow = 9 , Value = 1_000_000_000f , Unit = 'B' } ,
93- new { Pow = 6 , Value = 1_000_000f , Unit = 'M' } ,
94- new { Pow = 3 , Value = 1_000f , Unit = 'K' } ,
95- new { Pow = 0 , Value = 1f , Unit = '\0 ' }
92+ new { Value = 1_000_000_000f , Unit = 'B' } ,
93+ new { Value = 1_000_000f , Unit = 'M' } ,
94+ new { Value = 1_000f , Unit = 'K' }
9695 } ;
9796
98- var multiplier = powers . First ( x => number . ToString ( ) . Length > x . Pow ) ;
99- var simplifiedNumber = ( number / multiplier . Value ) ;
100- var roundValue = ( int ) float . Parse ( string . Format ( "{0:F1}" , simplifiedNumber ) ) ;
101-
102- // This is used in some cases to get the right power with its unit (e.g: 999_999_000 is rounded to 1.0B)
103- if ( roundValue > simplifiedNumber )
104- {
105- return ( roundValue * ( int ) multiplier . Value * ( isNegative ? - 1 : 1 ) ) . ToKiloFormat ( ) ;
106- }
107-
108- return ( isNegative ? "-" : "" ) + string . Format ( "{0:F1}" , simplifiedNumber ) + multiplier . Unit ;
97+ return powers
98+ . Where ( pow => Math . Abs ( Math . Round ( number / pow . Value , 3 ) ) >= 1f )
99+ . Select ( pow => string . Format ( "{0:F1}{1}" , number / pow . Value , pow . Unit ) )
100+ . First ( ) ;
109101 }
110102 }
111103}
0 commit comments