Can anyone give me some help on how to round half down in Visual Basic? I need 1.235 to be converted to 1.23 and NOT 1.24.
Asked
Active
Viewed 222 times
-4
-
2Read the documentation for the `Math.Round` or `Decimal.Round` method, depending on which one you're using. All the information you need is there. ALWAYS read the relevant documentation before posting a question. – user18387401 Aug 12 '22 at 11:47
-
using math.round value 1.235 Is Converted to 1.24 & by using Decimal.Round value 1.235 Is Converted to 1 – Max Aug 12 '22 at 11:49
-
@Max Yes, you can't use `Math.Round()` for this purpose if you're using .NET Framework or .NET Core <3.0 (at least not directly). See [this answer](https://stackoverflow.com/a/13522109/8967612) for more information. It's for C# but the logic is the same. You'll need to either use `Math.Floor()` with multiplication and division as demonstrated in the duplicate linked above, or you could write your own custom method that uses `Math.Round()` as demonstrated [here](https://stackoverflow.com/a/13575296/8967612). – 41686d6564 stands w. Palestine Aug 12 '22 at 11:54
-
On the other hand, if you're using .NET Core 3+ or .NET 5+, you can simply do `Math.Round(1.235, 2, MidpointRounding.ToZero)` or `.Round(1.235, 2, MidpointRounding.ToNegativeInfinity)` (depending on how you want to handle negative values). – 41686d6564 stands w. Palestine Aug 12 '22 at 11:59
2 Answers
1
What is in the comments,
Const numD As Integer = 100 'for 3 digits 1000, etc.
Dim d As Double = 1.235#
Dim d1 As Double
d1 = Math.Round(d, 2)
Stop
d1 = Math.Round(d, 2, MidpointRounding.AwayFromZero)
Stop
d1 = Math.Round(d, 2, MidpointRounding.ToEven)
Stop
d1 = Math.Sign(d) * Math.Floor(Math.Abs(d) * numD) / numD 'winner winner
Stop

dbasnett
- 11,334
- 2
- 25
- 33
1
Dim value As double = 1.235
value = Math.Floor(value * 100) / 100

Joel Coehoorn
- 399,467
- 113
- 570
- 794