1

I'm currently working on a program and im converting my java code into c# . but i'm having some trouble.

public double round(double value){
        BigDecimal b = new BigDecimal(value);
        b = b.setScale(2,BigDecimal.ROUND_UP);
        return (b.doubleValue());
    }

i wrote this converting code but i cant convert it to c#.BigDecimal type causes some problem and im totally new to .Net.Definitely need some help.

Edit : Ok buds i got it , sorry for the dumb question.

thecodekid
  • 135
  • 2
  • 2
  • 10
  • Looks like .NET doesn't have an equivalent of Java's BigDecimal -- [Stack Overflow](http://stackoverflow.com/questions/2863388/what-is-the-equivalent-for-java-class-bigdecimal-in-c). It has decimal, but that has only finite precision. Is that sufficient for what you want to do? – mgiuca Jan 26 '11 at 23:51
  • actually i don't need that type at all.all i need is to realize double rounding in the way i did with bigdecimal – thecodekid Jan 26 '11 at 23:55

2 Answers2

6

Here is a C# method that you can use instead:

public double round(double value){
    return Math.Round(value, 2, MidpointRounding.AwayFromZero);   
}

.Net's MidpointRounding.AwayFromZero is the equivalent of java's ROUND_UP.

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334
4

Couldn't you just do this to round to 2 fractional digits?

        double foo = 3.143;
        double fooRounded = Math.Round(foo, 2); 
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 1
    That will actually use `MidpointRounding.ToEven` by default, which will produce slightly different results than the `ROUND_UP` in the java original. – MusiGenesis Jan 27 '11 at 00:08
  • @MusiGenesis - Totally Agreed, I was just showing simple rounding with Math.Round, to exactly replicate the behavior as shown in OP's method above your updated answer should be the accepted one - hopefully he's still reading this. – BrokenGlass Jan 27 '11 at 00:17
  • You'd think the SO experience would teach someone like me the utter lack of value in nitpicking somebody else's code, but no ... – MusiGenesis Jan 27 '11 at 00:30