Reputation: 365
What is the syntax to round up a decimal leaving two digits after the decimal point?
Example: 2.566666 -> 2.57
Upvotes: 16
Views: 108672
Reputation: 26
Math.Ceiling((14.512555) * 100) / 100
Dot net will give you 14.52
. So, you can use above syntax to round the number up for 2 decimal numbers.
Upvotes: 0
Reputation: 61
The basic function for rounding up is Math.Ceiling(d), but the asker specifically wanted to round up after the second decimal place. This would be Math.Ceiling(d * 100) / 100. For example, it may multiply 46.5671 by 100 to get 4656.71, then rounds up to get 4657, then divides by 100 to shift the decimal back 2 places to get 46.57.
Upvotes: 2
Reputation: 41588
Math.Round is what you're looking for. If you're new to rounding in .NET - you should also look up the difference between AwayFromZero and ToEven rounding. The default of ToEven can sometime take people by surprise.
dim result = Math.Round(2.56666666, 2)
Upvotes: 7
Reputation: 129
Here is how I do it:
Private Function RoundUp(value As Double, decimals As Integer) As Double
Return Math.Ceiling(value * (10 ^ decimals)) / (10 ^ decimals)
End Function
Upvotes: 12
Reputation: 60
I do not understand why people are recommending the incorrect code below:
Dim r As Decimal = Math.Ceiling(d * 100D) / 100D
The correct code to round up should look like this:
Dim r As Double = Math.Ceiling(d)
Upvotes: -2
Reputation: 700780
If you want regular rounding, you can just use the Math.Round
method. If you specifially want to round upwards, you use the Math.Ceiling
method:
Dim d As Decimal = 2.566666
Dim r As Decimal = Math.Ceiling(d * 100D) / 100D
Upvotes: 16
Reputation: 416131
Math.Round()
, as suggested by others, is probably what you want. But the text of your question specifically asked how to "roundup"[sic]. If you always need to round up, regarless of actual value (ie: 2.561111 would still go to 2.57), you can do this:
Math.Ceiling(d * 100)/100D
Upvotes: 2
Reputation: 630607
You can use System.Math
, specifically Math.Round()
, like this:
Math.Round(2.566666, 2)
Upvotes: 3