开发者

How to round a decimal amount, in c sharp, to a nearest fractional value given by users?

Requirement

User has option to choose fractional val开发者_开发技巧ue as a rule. For example 0.5, or 0.01, or 0.33, or 0.1.

Amount is for example 12.46 and rounding rule is 0.01.

I am not sure if i have explained it correctly.

Any answer is highly appreciated. Khankooouuu in advance.


public class Test
{
    static double round(double what, double to)
    {
        return to * Math.Round(what/to);
    }

    public static void Main()
    {
        Console.WriteLine(round(3.5, 1));
        Console.WriteLine(round(3.44, 1));
        Console.WriteLine(round(3.44, 0.1));
        Console.WriteLine(round(1.68, 0.33));
        Console.WriteLine(round(1.59, 0.33));
    }
}

outputs

4
3
3.4
1.65
1.65


You can round a decimal by using the Decimal.Round() method with an overload of Decimal and an integer for how many decimal places. See Here.

As for the part to see how many decimal places the user wants to use if they put in a decimal value, you can convert that to a string and count the characters after the decimal point:

decimal UserDecimal;
string UserString = UserDecimal.ToString();
int DecimalPlaces = UserString.SubString(UserString.IndexOf(".")).Length;

At the end of all that, DecimalPlaces will be the amount of decimal places the user has implicitly requested with their inputed decimal value.

This what you're looking for??

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜