Best way to remove trailing zeros from a Decimal - vb.net

I have a calculation that returns a decimal with a maximum of two decimal places. What I'd like to achieve is a result that doesn't include decimal zeros, so 8.00 is shown as 8, 8.10 is shown as 8.1 and 8.12 is shown as 8.12.
I've been all over the math functions and can't find anything to achieve this - can anyone point me in the right direction?

As Benjamin Leinweber pointed out in one of the comments it's probably a product of it being displayed as a string. That said, you could take the duct tape approach and just lop off the trailing digits you don't want like this (who doesn't love duct tape every so often):
' Hacky, I did this because Visual Studio removes the 0 in the editor
Dim num As Decimal = CDec("8.10")
' This will now output 8.10
Console.WriteLine(num)
' Put it in a string then trim off the 0's and then the decimal place if it then happens to be at the end
Dim buf As String = num.ToString
buf = buf.TrimEnd("0")
buf = buf.TrimEnd(".")
' This will output 8.1
Console.WriteLine(buf)

Are you talking about the VB Decimal data type? If so then read this from the MSDN documentation...
Trailing Zeros. Visual Basic does not store trailing zeros in a Decimal literal.
However, a Decimal variable preserves any trailing zeros acquired computationally.
The following example illustrates this.
Dim d1, d2, d3, d4 As Decimal
d1 = 2.375D
d2 = 1.625D
d3 = d1 + d2
d4 = 4.000D
MsgBox("d1 = " & CStr(d1) & ", d2 = " & CStr(d2) &
", d3 = " & CStr(d3) & ", d4 = " & CStr(d4))
The output of MsgBox in the preceding example is as follows:
d1 = 2.375, d2 = 1.625, d3 = 4.000, d4 = 4
So since the Decimal data type holds on to significant digits in a calculation then you may want to convert the data type to double and use a custom format like {0:#.##} for display
MSDN Decimal Data Type

.ToString("###") or however many octothorpes for however many to the left of the decimal.
If you want to have... say, 2 decimal places:
.ToString("###.##")

You can do it by using TrimEnd function :
Dim number1 As Double = 8.0
Dim number2 As Double = 8.1
Dim number3 As Double = 8.12
Console.WriteLine(number1.ToString("N2").TrimEnd("0"c).TrimEnd("."c))
Console.WriteLine(number2.ToString("N2").TrimEnd("0"c).TrimEnd("."c))
Console.WriteLine(number3.ToString("N2").TrimEnd("0"c).TrimEnd("."c))
Consider that formatting with "F0" will remove 1000 separators too.

From what you are describing, it sounds like you are using a Fixed-point format when you should be using a Number format or a General format.
This sample code taken from the MSDN shows how to use the Number format:
Dim dblValue As Double = -12445.6789
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture))
' Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1", _
CultureInfo.CreateSpecificCulture("sv-SE")))
' Displays -12 445,7
Dim intValue As Integer = 123456789
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture))
' Displays 123,456,789.0
For a complete list of formatters, have a look at this MSDN article.

This solution applies to different cultures and works with integer numbers ends with Zero
`
Public Module DecimalExt
<Extension()>
Function ToStringWithoutZeros(ByRef value As Decimal) As String
Dim buf As String = value.ToString("n10")
buf = buf.TrimEnd("0").TrimEnd(",").TrimEnd(".")
Return buf
End Function
End Module
`

I think You can try with Val Function
Like we we have a Decimal Value like
8.00
8.01
8.590
Then after using the Val() function it will convert this decimals to
Dim number as Decimal = 8.00
`Msgbox(Val(number))` // will gives you 8

Related

How do I make my percentages have 2 decimal points?

I have looked at other posts about this but i just can't get my head around it and wanted to ask specifically for my scenario. I have written a Visual Basic console application and I am trying to get my percentages to have two decimal places on them as they're just rounding up to the nearest whole number. Here is the code :
Console.Write("Enter the percentage you want to work out: ")
Dim Percentage As Integer
Percentage = Console.ReadLine()
Console.Write("What would you like to work out " & Percentage & "% of? ")
Dim Number As Integer
Number = Console.ReadLine()
Dim PercentageNumberResult As Integer
PercentageNumberResult = Number / 100 * Percentage
Console.Write(Number & " ÷ 100 × " & Percentage & " = " & PercentageNumberResult)
Console.ReadLine()
Any help would be appreciated, thanks!
The problem is due to PercentageNumberResult being an integer.
Make PercentageNumberResult a double :
Dim PercentageNumberResult As Double
PercentageNumberResult = Number / 100 * Percentage
You could then use Math.Round if needed. Also you should turn on Option Strict this will help solving the problem.
If you want to convert a number to a String then you call ToString on that number. If you want a specific format then you pass the appropriate format specifier as an argument when calling ToString. You should read the relevant documentation to learn all the possible format specifiers.
In this case, you display a number as a percentage using the "p" or "P" specifier and you can add a number to specify the number of decimal places. e.g.
Dim x = 13
Dim y = 1000
Dim z = x / y
Dim s = z.ToString("P2")
After executing that code, s will contain "1.30%".
If you don't actually want the "%" symbol in the output then you can multiply by 100 and use a different format specifier, e.g.
Dim x = 13
Dim y = 1000
Dim z = 100 * x / y
Dim s = z.ToString("N2")
After executing that code, s will contain "1.30".

Converting a string in Datagridview to Decimal

I have a Colum with in a dataGridview with Amount in the format “5 187.00”
I am trying to sum-up the Colum and have the result in a viable but what happens is , the system only picks the value “5” not “5,187.00” as I expected. So I am thinking the space in between 5 and 1 is the problem.
My question is how do I prevent the space, or convert the entry to decimal.
I have tried using
Dim num as String
Num = “5 187.00”
Num =num.Replace(“ ”, “”)
Cell value = Num
But this no not responding
Let me know if anyone can help.
Thank you
We are not sure what space it is. (can be a tab also)
Use Regex class as shown in below example
Dim num As String = "5 678.90"
Dim cellValue As Decimal = 0.0
num = Regex.Replace(num, "\s", "")
cellValue = Convert.ToDecimal(num)
You have to import
Imports System.Text.RegularExpressions

How do I convert integer to 4-digit hex string?

I need to convert a 2-byte signed integer into a string of it's hex equivalent, but I need the string to be 4 characters. I've tried the Hex() function but when I convert 0 or say, 10, the result is 0 or A. I need the result to be 0000 or 000A. Any tips or advice?
It is just
Dim hexS As String = i.ToString("X4")
This is well explained in the The Hexadecimal (X) Format specifier.
The 4 after the X specifies how many chars you want in the output and if there are not enough chars, the missing ones are supplied as an appropriate number of "0".
Since you also tagged the question VBA, here is a VBA way to do it
Right("0000" & Hex(i), 4)
Use
Dim i As Integer = 10
Dim hexS As String = i.ToString("X4")
If you are deadset on using Hex as opposed to string formatting then you could use:
Dim Number As Integer
Dim Output As String
Number = 10
Output = ("000" & Hex(Number))
Output = Output.Substring(Output.Length - 4, 4)
Console.WriteLine(Output)
Alternatively make use of string formatting for numbers as so:
Output = Number.ToString("X4")
Console.WriteLine(Output)
The output in both cases with be 000A.
The VB way
Format(i, "X4")
or
Hex(i).PadLeft(4, "0"c)
In Visual Studio 2015:
s = $"{i:X4}"

using IndexOf in Mid function

Perhaps this is a simple solution for most, but I can't get this to work like it should according to syntax.
I have this line of text "Part Number123456Price$50.00"
I want to pull the part number out of it, so I use this function...
str = Mid(str, str.IndexOf("Part Number") + 12, str.IndexOf("Price"))
My results are str = "123456Price$50.0" every time. I know the part number can vary in length so I need a solid solution of pulling this out.
It can be confusing to mix the legacy VB string methods (such as Mid) with the .Net string methods (like IndexOf). The VB methods use 1 as the index of the first character while the .Net methods use 0.
The following code will extract the part number from a string
Dim str As String = "Part Number123456Price$50.00"
Dim iPart As Integer = str.IndexOf("Part Number") + 11
Dim iPrice As Integer = str.IndexOf("Price")
str = str.Substring(iPart, iPrice - iPart).Trim
The Mid() function of Visual Basic is documented as having three arguments: (1) a string, (2) the beginning location in the string, and (3) the number of characters to copy.
So if your string is "Part Number123456Price$50.00" and you want to pull the part number as a series of digits, the "123456" part of the string, using the Mid() function then you need to find the beginning of the part number digit string and to then know the number of digits.
If your string is in the variable str then you can find the offset by something like str.IndexOf("Number") + len("Number") which will provide the offset to after the string "Number".
Next you need to find the number of digits so you would do something like str.IndexOf("Price") to find where the text "Price" begins and then subtract from that offset the offset of where the digits begin.
The result of all of this is you need a bit of code something like the following. I have not tested this source as I am not a VB programmer so it may need a tweak and you might want to put some checks on data validity as well.
Dim TextNumber as String = "Number"
Dim TextPrice as String = "Price"
iOffset = str.IndexOf(TextNumber) + len(TextNumber)
str = Mid(str, iOffset, str.IndexOf(TextPrice) - iOffset)
Alternatively, if Price is always the format $00.00, this will also work.
Dim str as String = "Part Number123456Price$50.00"
str = str.Remove(str.IndexOf("Price"))

VBA change string with decimal to number with decimal

I have a field in an access database as TEXT. the text has decimals such as 100.00000. need to run calcs on these with the decimals present. Ive been working with the SQL statement and CAST functions and ive had no luck. All I get is whole numbers with no decimals. I've resorted to VBA and I am still getting the same results. every result is whole numbers. I would prefer 5 (FIVE) decimal places.
such as 100.00000 and not "100".
I've tried the split function in VBA and re assembling the 2 strings into a number with the decimal present and still no luck.
The code below pulls in whole numbers only - I need decimal places!! thank you
Function numChange(input1 As String) As Integer
Dim output As Integer
If input1 = "" Then
input1 = 0
End If
output = Format(input1, Number)
numChange = output
End Function
after decimal if no zero will mean a thing, but if you have 100.00001 this will return the same.
Modified:
Function numChange(input1 As String) As Double
Dim output As Double
If input1 = "" Then
input1 = 0
End If
output = Format(input1, "0.00000")
numChange = output
End Function