0

I have been working on a system for a while now, and the client has been testing it. They want the system to now Round up keeping two decimal places. Can someone help as i seem to be having trouble with Math.Ceiling and converting the numbers to decimal. My code is below.

Line 2 is where the change needs to be made and the figure needs to round up keeping 2 decimal places.

float fcharge = Convert.ToSingle(dr["total_charge_weight"]) * Convert.ToSingle(dr["H_unit_rate"]);
decimal dcharge = Math.Round(Convert.ToDecimal(fcharge), 2);
float charge = Convert.ToSingle(dcharge); 
Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
JNR_Prog123
  • 133
  • 1
  • 3
  • 14
  • can you provide a example with input and expected output data? – fubo Sep 09 '16 at 09:23
  • What is wrong with your code ? – Zein Makki Sep 09 '16 at 09:25
  • @fubo input will be 123.877 expected output 123.90 – JNR_Prog123 Sep 09 '16 at 09:28
  • Did you try to _decimal dcharge = Math.Round(Convert.ToDecimal(fcharge), 1);_ ? – Steve Sep 09 '16 at 09:30
  • I have it just drops away numbers after the decimal until there is 1 or 2 left – JNR_Prog123 Sep 09 '16 at 09:32
  • 2
    Note that 123.90 is the same as 123.9 from the point of view of the decima/float variable. It is how you display it that makes the difference between 1 or 2 decimals. After rounding to 1 decimal then use ToString("N2") to show two decimals – Steve Sep 09 '16 at 09:35
  • @Steve the client is very specific that only the decimal is to either round up or drop away example 123.505 output 123.51 and 123.515 output 123.50, the 5 will round up but the 2 will drop away. – JNR_Prog123 Sep 09 '16 at 09:46

1 Answers1

0

Wouldn't this do?

 public static float RoundUp(float number, int decimalPlaces)
 {
     var scale = Math.Pow(10, decimalPlaces);
     return (float)(Math.Ceiling(number * scale) / scale);
 }

Things to consider:

  1. You are required to roud up. Math.Round does not do that.
  2. There is no need to use Convert, simply cast.
  3. There is no need to convert to decimal, you are throwing it away when converting back to float; use the implicit conversion to double and only cast back to float if its a requirement.
InBetween
  • 32,319
  • 3
  • 50
  • 90