这个function主要是用来format传入的浮点型的字符串。

strFloat:传入的浮点型字符串;

minDecimals: 最小保留小数位;

例如:

传入 strFloat =  "0.1";   minDecimal = 2

则返回的结果为:0.10

传入 strFloat =  "0.123";   minDecimal = 2

则返回的结果为:0.123

传入 strFloat =  ".1";   minDecimal = 2

则返回的结果为:0.10

传入 strFloat =  "0001.10000";   minDecimal = 2

则返回的结果为:1.10

等等情况……

 minDecimals)
{
    //This is a recursive function and order of operations is important

    
//No formatting on Null or Empty input
    if(strFloat == String.Empty)
        
return strFloat;

    
//find the current position of the decimal point
    int at = strFloat.LastIndexOf(".");

    
//if no decimal point, append decimal point and min zeros and return 
    if(at < 0)
            
if(minDecimals > 0)
                
return strFloat + ".".PadRight(1 + minDecimals, '0');
            
else
                
return strFloat;

    
//add a zero to the left of decimal point if no int value
    else if(at == 0)
        
return FormatMinDecimals("0" + strFloat, minDecimals);

    
//if no minimum, and decimal point is the last character, remove it
    else if(at == strFloat.Length - 1 && minDecimals == 0)
        
return FormatMinDecimals(Left(strFloat, strFloat.Length - 1), minDecimals);

    
//remove leading zeros if more than one
    else if(at > 1 && Left(strFloat, 1== "0")
        
return FormatMinDecimals(Right(strFloat, strFloat.Length - 1), minDecimals);

    
//append one zero "while" has less than min decimal places
    else if(at >= strFloat.Length - minDecimals)
        
return FormatMinDecimals(strFloat + "0", minDecimals);

    
//return if it has minimum decimal places or has more but with no trailing zeros
    else if(at == strFloat.Length - minDecimals - 1 || Right(strFloat, 1!= "0")
        
return strFloat;

    
//remove trailing zeros
    else
        
return FormatMinDecimals(Left(strFloat, strFloat.Length - 1), minDecimals);

}

相关文章: