how to chop numbers in vb.net windows app? - vb.net

I want my program to enter a decimal that will output in 4 decimal places by not rounding the inputed number
input: 0.6363636364
output: 0.6363

For completeness, since the OP requested a VB solution, here's the Decimal extension based on Tim Lloyd's answer to Truncate Two decimal places without rounding:
Module MyExtensions
<System.Runtime.CompilerServices.Extension>
Public Function TruncateDecimal(d As Decimal, decimals As Integer) As Decimal
Select Case True
Case decimals < 0
Throw New ArgumentOutOfRangeException("decimals", "Value must be in range 0-28.")
Case decimals > 28
Throw New ArgumentOutOfRangeException("decimals", "Value must be in range 0-28.")
Case decimals = 0
Return Math.Truncate(d)
Case Else
Dim IntegerPart As Decimal = Math.Truncate(d)
Dim ScalingFactor As Decimal = d - IntegerPart
Dim Multiplier As Decimal = Math.Pow(10, decimals)
ScalingFactor = Math.Truncate(ScalingFactor * Multiplier) / Multiplier
Return IntegerPart + ScalingFactor
End Select
End Function
End Module
Usage:
Dim Value As Decimal = 0.6363636364
Value = Value.TruncateDecimal(4)

Related

Vb.net how to get the number after decimal places

in Vb.net how to get the number after decimal places.
I tried below code.
Dim number As Decimal = 143.500
Dim wholePart As Integer = Decimal.Truncate(number)
Dim fractionPart As Decimal = number - wholePart
Dim secondPart3 As Integer
secondPart3 = Replace(fractionPart, "0.", "0")
then the result is coming 500, but when i tried 143.050 its giving 50 it should show 050
Thanks
Thanks everyone. i got it with sample below code
Dim numar As Double
If Double.TryParse(TextBox1.Text, numar) Then
Dim rmndr As Double
rmndr = numar Mod 1
If rmndr = 0 Then
Else
TextBox2.Text = Split(CStr(TextBox1.Text), ".")(1)
End If
End If
Your solution (here) is unnecessarily complex. You were on the right track in your original post, but conflated numeric values with formatted string values. Because while 050 are 50 are the same numeric value, when you implicitly call ToString on the value (or explicitly with the wrong formatting) then you would always get 50 because the prefixing 0 is unnecessary when working with numeric values.
What you should do is:
Get the integral digits of the decimal value
Convert the underlying decimal value to a String
(optionally) Format the String specifying the level of precision
Drop the integral digits off converted string
Here is an example:
Private Function GetFractionalDigits(value As Decimal) As String
Dim integralDigits = Decimal.Truncate(value)
Return value.ToString().Remove(0, integralDigits.ToString().Length + 1)
End Function
Private Function GetFractionalDigits(value As Decimal, precisionSpecifier As Integer) As String
If (precisionSpecifier < 0) Then
Throw New ArgumentOutOfRangeException("precisionSpecifier", "precisionSpecifier cannot be less than 0")
End If
Dim integralDigits = Decimal.Truncate(value)
Return value.ToString("N" & precisionSpecifier).Remove(0, integralDigits.ToString().Length + 1)
End Function
Fiddle: https://dotnetfiddle.net/SBOXG0

How to create a random decimal between 0 and 1 vb.net

I need a random decimal between 0 and 1 in VB.NET
Dim value As Decimal = CInt(Int((1 * Rnd()) + 0))
I'm trying this but it's just saving as 0. It's definitely something I'm doing wrong but I'm not sure yet.
It should be between 0 and 1, but it's just returning 0.
CInt will convert your Decimal value to an Integer value. Besides, Rnd is so 15 years ago, use Random.NextDouble instead:
Dim r As New Random() 'Should be declared at the topmost level
Dim value As Double = r.NextDouble()
Fiddle: Live Demo
The function Rnd already returns a decimal number between 0 and 1. (Docs)
Just use:
Dim Value as Decimal = Rnd()
RND Class already generates a decimal
Dim RandomOperator as new Rnd()
Dim Value as double = RandomOperator()

Round up to the nearest multiple of a number

This question has already been asked for the C++ language but I need a function for VBA. I tried converting the C++ function to VBA, but it doesn't return the right values.
I need a function that does the following:
RoundUp(23.90, 5)
'return 25
RoundUp(23.90, 10)
'return 30
RoundUp(23.90, 20)
'return 40
RoundUp(23.90, 50)
'return 50
RoundUp(102.50, 5)
'return 105
RoundUp(102.50, 20)
'return 120
Here's what I have so far. It works most of the time, but returns incorrect values for numbers that are less than .5 less than the multiple. So the problem seems to be a rounding problem with how I'm calculating the remainder value.
Public Function RoundUp(dblNumToRound As Double, lMultiple As Long) As Double
Dim rmndr As Long
rmndr = dblNumToRound Mod lMultiple
If rmndr = 0 Then
RoundUp = dblNumToRound
Else
RoundUp = Round(dblNumToRound) + lMultiple - rmndr
End If
End Function
For Example:
RoundUp(49.50, 50)
'Returns 49.50 because rmndr = 0
I'd simply divide by the lMultiple, round up and multiply again.
Assuming you indeed always want to round up (also for negative numbers):
Public Function RoundUp(dblNumToRound As Double, lMultiple As Long) As Double
Dim asDec as Variant
Dim rounded as Variant
asDec = CDec(dblNumToRound)/lMultiple
rounded = Int(asDec)
If rounded <> asDec Then
rounded = rounded + 1
End If
RoundUp = rounded * lMultiple
End Function
I'm not actually a VBA programmer, so this might need a tweaked comma or two. However the important thing is:
Use Decimal (variant subtype) for precision
Let VB do the math for you
Worth trying WorksheetFunction.Ceiling method (Excel)
WorksheetFunction.Ceiling(27.4,5)
Above example will return 30. Here is Link:
https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.ceiling
A far simpler solution is to add .5 to the number before rounding:
1.1 -> Round(1.1+.5, 0) -> 2

Decimal places in a number in VB.NET

How do I check how many decimal places a number has in VB.NET?
For example: Inside a loop I have an if statement and in that statement I want to check if a number has four decimal places (8.9659).
A similar approach that accounts for integer values.
Public Function NumberOfDecimalPlaces(ByVal number As Double) As Integer
Dim numberAsString As String = number.ToString()
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
If indexOfDecimalPoint = -1 Then ' No decimal point in number
Return 0
Else
Return numberAsString.Substring(indexOfDecimalPoint + 1).Length
End If
End Function
Dim numberAsString As String = myNumber.ToString()
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
Dim numberOfDecimals As Integer = _
numberAsString.Substring(indexOfDecimalPoint + 1).Length
Public Shared Function IsInSignificantDigits(val As Double, sigDigits As Integer)
Dim intVal As Double = val * 10 ^ sigDigits
Return intVal = Int(intVal)
End Function
For globalizations ...
Public Function NumberOfDecimalPlaces(ByVal number As Double) As Integer
Dim numberAsString As String = number.ToString(System.Globalization.CultureInfo.InvariantCulture)
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
If (indexOfDecimalPoint = -1) Then ' No decimal point in number
Return 0
Else
Return numberAsString.Substring(indexOfDecimalPoint + 1).Length
End If
End Function
Some of the other answers attached to this question suggest converting the number to a string and then using the character position of the "dot" as the indicator of the number of decimal places. But this isn't a reliable way to do it & would result in wildly inaccurate answers if the number had many decimal places, and its conversion to a string contained exponential notation.
For instance, for the equation 1 / 11111111111111111 (one divided by 17 ones), the string conversion is "9E-17", which means the resulting answer is 5 when it should be 17. One could of course extract the correct answer from the end of the string when the "E-" is present, but why do all that when it could be done mathematically instead?
Here is a function I've just cooked up to do this. This isn't a perfect solution, and I haven't tested it thoroughly, but it seems to work.
Public Function CountOfDecimalPlaces(ByVal inputNumber As Variant) As Integer
'
' This function returns the count of deciml places in a number using simple math and a loop. The
' input variable is of the Variant data type, so this function is versatile enougfh to work with
' any type of input number.
'
CountOfDecimalPlaces = 0 'assign a default value of zero
inputNumber = VBA.CDec(inputNumber) 'convert to Decimal for more working space
inputNumber = inputNumber - VBA.Fix(inputNumber) 'discard the digits left of the decimal
Do While inputNumber <> VBA.Int(inputNumber) 'when input = Int(input), it's done
CountOfDecimalPlaces = CountOfDecimalPlaces + 1 'do the counting
inputNumber = inputNumber * 10 'move the decimal one place to the right
Loop 'repeat until no decimal places left
End Function
Simple...where n are the number of digits
Dim n as integer = 2
Dim d as decimal = 100.123456
d = Math.Round(d, n);
MessageBox.Show(d.ToString())
response: 100.12

Split a 'Decimal' in VB.NET

I am sure this is a very simple problem, but I am new to VB.NET, so I am having an issue with it.
I have a Decimal variable, and I need to split it into two separate variables, one containing the integer part, and one containing the fractional part.
For example, for x = 12.34 you would end up with a y = 12 and a z = 0.34.
Is there a nice built-in functions to do this or do I have to try and work it out manually?
You can use Math.Truncate(decimal) and then subtract that from the original. Be aware that that will give you a negative value for both parts if the input is decimal (e.g. -1.5 => -1, -.5)
EDIT: Here's a version of Eduardo's code which uses decimal throughout:
Sub SplitDecimal(ByVal number As Decimal, ByRef wholePart As Decimal, _
ByRef fractionalPart As Decimal)
wholePart = Math.Truncate(number)
fractionalPart = number - wholePart
End Sub
(As Jon Skeet says), beware that the integer part of a decimal can be greater than an integer, but this function will get you the idea.
Sub SlipDecimal(ByVal Number As Decimal, ByRef IntegerPart As Integer, _
ByRef DecimalPart As Decimal)
IntegerPart = Int(Number)
DecimalPart = Number - IntegerPart
End Sub
Use the Jon version if you are using big numbers.
Simply:
DecimalNumber - Int(DecimalNumber)
Fractional and decimal part of a number have different significance when a number is above zero or below zero. Therefore, you have to consider both cases.
I suggest using the below code:
Dim dbl as double = 13.067
Dim int1 As Integer = 0
Dim fraction As Double = 0
If dbl >= 0 Then
int1 = Math.Floor(dbl)
ElseIf dbl < 0 Then
int1 = Math.Ceiling(dbl)
End If
fraction = dbl - int1
fraction holdes 0.067, and int1 holds 13 .
Floor and Ceiling, round any fractional number to the lowest, and highest consecutive integer, respectively.