Click here to Skip to main content
15,887,464 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my need is the user input is 1.53 means the output will come 1.50 like below cases

user input       Expectedoutput

1.20          1.50
1.50          1.50
1.60          2.00



how to achive this output

What I have tried:

i have tried math. round Math.Round(10.45,1,MidpointRounding.ToEven) but i could not achive the output



I have found the solution using below method

C#
double  Expected_result1 = 25.51;
value = Expected_result1 - Math.Floor(Expected_result1);// get fraction
Expected_result1 = ((value >= 0.01) && (value <= 0.50)) ? (Math.Floor(Expected_result1) + 0.5) : Math.Ceiling(Expected_result1);
Posted
Updated 7-Sep-16 4:49am
v3

1 solution

This is not how Math.Round works. Usually, rounding is done at a specific decimal position. So if you specify 1 decimal for rounding purpose, then essentially the answer would be the nearest number with 1 decimal.

Then you have some options to specify mid-point rounding. This is generally more useful for financial applications to reduce cumulative error.

If you want to round to a specific multiple like 0.5, then you have to add some extra code. For example, you might multiply by 2, round to unit and then divide by 2.

Here is the code with one operation per line and value in comment.

C#
var value = 10.45;             // 10.45
value *= 2.0;                  // 20.90
value = Math.Round(value, 0);  // 21.00
value /= 2.0;                  // 10.50


However, how do you expect 1.20 to be rounded to 1.50. With above code, it will round to 1.00. Replacing Math.Round by Math.Ceiling might be what you want (however, you cannot specify the number of decimals).

Alternatively, you might want to add 0.5 before calling Math.Round. In that case, mid-point rounding might be more important.

For information on how rounding works, it might be useful to read documentation as it is very clear in documentation:MidpointRounding Enumeration (System)[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900