Format decimal to store in a .txt - vb.net-2010

I want to put a decimal number like 76,50 in a textbox. Add it like this in a listbox (that already works). I would save it to a .txt file, but when I open the .txt file I want the number to be like 07650 (only in the .txt file). When I open it back in my form it has to be 76,50 again. I already have the following in VB.net:
Public Function FormatDecimal(ByVal perc As Decimal, ByVal PercOut As Integer) As String
Dim percent As Integer = 100
Dim percAsString As String = perc.ToString("00000")`
perc = perc * 100
PercOut = Convert.ToInt32(perc)
Do While txtPercentage.Text.Length < 5
perc = 0 + PercOut
Loop
Return percAsString
End Function
I don't know where to put it; when I save the form to a .txt it stops.
I have been looking on the website for an answer but couldn't find one. Can you help me?

In this loop if the txtPercentage text is 6,50 you never exit
Do While txtPercentage.Text.Length < 5
perc = 0 + PercOut
Loop
If your intention is just to have a decimal number with only two decimals formatted as a string in 5 characters without decimal separator then
Public Function FormatDecimal(ByVal perc As Decimal) As String
Return (perc * 100).ToString("00000")
End Function

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

Progress bar with VB.NET Console Application

I've written a parsing utility as a Console Application and have it working pretty smoothly. The utility reads delimited files and based on a user value as a command line arguments splits the record to one of 2 files (good records or bad records).
Looking to do a progress bar or status indicator to show work performed or remaining work while parsing. I could easily write a <.> across the screen within the loop but would like to give a %.
Thanks!
Here is an example of how to calculate the percentage complete and output it in a progress counter:
Option Strict On
Option Explicit On
Imports System.IO
Module Module1
Sub Main()
Dim filePath As String = "C:\StackOverflow\tabSeperatedFile.txt"
Dim FileContents As String()
Console.WriteLine("Reading file contents")
Using fleStream As StreamReader = New StreamReader(IO.File.Open(filePath, FileMode.Open, FileAccess.Read))
FileContents = fleStream.ReadToEnd.Split(CChar(vbTab))
End Using
Console.WriteLine("Sorting Entries")
Dim TotalWork As Decimal = CDec(FileContents.Count)
Dim currentLine As Decimal = 0D
For Each entry As String In FileContents
'Do something with the file contents
currentLine += 1D
Dim progress = CDec((currentLine / TotalWork) * 100)
Console.SetCursorPosition(0I, Console.CursorTop)
Console.Write(progress.ToString("00.00") & " %")
Next
Console.WriteLine()
Console.WriteLine("Finished.")
Console.ReadLine()
End Sub
End Module
1rst you have to know how many lines you will expect.
In your loop calculate "intLineCount / 100 * intCurrentLine"
int totalLines = 0 // "GetTotalLines"
int currentLine = 0;
foreach (line in Lines)
{
/// YOUR OPERATION
currentLine ++;
int progress = totalLines / 100 * currentLine;
///print out the result with the suggested method...
///!Caution: if there are many updates consider to update the output only if the value has changed or just every n loop by using the MOD operator or any other useful approach ;)
}
and print the result on the same posititon in your loop by using the SetCursor method
MSDN Console.SetCursorPosition
VB.NET:
Dim totalLines as Integer = 0
Dim currentLine as integer = 0
For Each line as string in Lines
' Your operation
currentLine += 1I
Dim Progress as integer = (currentLine / totalLines) * 100
' print out the result with the suggested method...
' !Caution: if there are many updates consider to update the output only if the value has changed or just every n loop by using the MOD operator or any other useful approach
Next
Well The easiest way is to update the progressBar variable often,
Ex: if your code consist of around 100 lines or may be 100 functionality
after each function or certain lines of code update progressbar variable with percentage :)

Is possible to ignore the TextBox?

I'm creating a program to calculate the average. There are 12 TextBox and I want to create the possibility to leave some fields blank. Now there are only errors and the crash of the program. Is possible to create that?
This is part of code:
ItalianoScritto = (TextBox1.Text)
MatematicaScritto = (TextBox2.Text)
IngleseScritto = (TextBox3.Text)
InformaticaScritto = (TextBox4.Text)
ScienzeScritto = (TextBox5.Text)
FisicaScritto = (TextBox6.Text)
MediaScritto = (ItalianoScritto + MatematicaScritto + IngleseScritto + InformaticaScritto + ScienzeScritto + FisicaScritto) / 6
Label10.Text = Str(MediaScritto)
If i leave blank the textbox1 when I click on the button to calculate the average Vb says Cast not valid from the string "" to type 'Single' and the bar of te textbox1 become yellow
I would do the following:
Iterate over the textboxes and check if you can parse the value into an iteger. If yes, add it to a value list.
Then add all values from that list and divide it by the number of cases.
It is faster than big if-statements and resilient against error
dim TBList as new list(of Textbox)
'add your textboxes to the list here
TbList.add(Textbox1)
...
dim ValList as new List(Of Integer)
for each elem in Tblist
dim value as integer
If integer.tryparse(elem.text,value)=True
ValList.add(Value)
else
'report error or do nothing
end if
next
dim Result as Integer
Dim MaxVal as Integer =0
for each elem in ValList
Maxval +=elem
next
Result = MaxVal / ValList.count
If you need support for point values, just choose double or single instead of Integer.
Also: regardless what you do -CHECK if the values in the textboxes are numbers or not. If you omit the tryparse, somebody will enter "A" and your app will crash and burn
Also: You OPTION STRICT ON!
You just have to check if the TextBox is blank on each one before using the value:
If TextBox7.TextLength <> 0 Then
'Use the value inside
End If
The way to do it depends a lot of your code. You should consider editing your question giving more information (and code) in order to us to help you better.

Decimal points handling within textbox in an excel form

I want to display a number in a textbox within an excel form. report, however I only want to show any decimal points if they are present and the I only want to show 2 decimal places.
e.g. if the number is 12 then I want to show 12
If the number is 12.1 then I want to show 12.10
If the number is 12.126 then I want to show 12.13
At the moment i have the below code and it is not showing me decimal points:
Me.Amount.Value = Format(Me.Amount, "#,###")
You could write a function to conditionally return one of two format strings:
Function GetFormatString(varValue As Variant) As String
Dim dblValue As Double
If IsNumeric(varValue) Then
dblValue = CDbl(varValue)
If dblValue = Int(dblValue) Then
GetFormatString = "#,###"
Else
GetFormatString = "#,###.00"
End If
End If
End Function
Private Sub Amount_AfterUpdate()
Dim strFormat As String
strFormat = GetFormatString(Me.Amount.Value)
Me.Amount.Value = Format(Me.Amount.Value, strFormat)
End Sub

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