Reputation: 20494
I would like to format a Double
number with undetermined decimal precisión (eg. value.ToString("n2")
) but eliminating/discarding the decimals in case of all the decimals are 0,
or in other words, return an integer string instead of a decimal string in case of all its decimals are zeroes.
How I could solve the decimal formatting problem explained above?. (please, see the Remarks)
This code will produce the string 1,00
, but it should produce the string 1
:
Dim value As Double = 1.0R
Dim format As String = value.ToString("n2", CultureInfo.CurrentCulture.NumberFormat)
Debug.WriteLine(format)
This code will produce the string 1,01
, doesn't need changes because it has a non-zero decimal:
Dim value As Double = 1.01R
Dim format As String = value.ToString("n2", CultureInfo.CurrentCulture.NumberFormat)
Debug.WriteLine(format)
Just another example of the expected formatting with a decimal precision of 2:
1
1,01
...
1,09
1,10 - Note the last zero is not eaten.
1,11
...
2
I've been reading these docs on MSDN but I didn't seen how to solve that.
Double.ToString Method (String)
Standard Numeric Format Strings
NumberFormatInfo.NumberDecimalDigits Property .
· I'm looking for the proper and efficient way to do this, I'm aware of doing a Substring
or things like that on the resulting string to search or count the resulting zeroes.
· I would like to keep using my current culture's NumberFormat
, if that matters.
· I will clarify that in my real scenario I'm using random numbers then I can't know whether the value to format will have zero decimals (1,00) or non-zero decimals (1,99) and/or its decimal precision/length.
Upvotes: 1
Views: 654
Reputation: 101152
You can use something like "0.##"
as your format string:
Dim values = {1.0000R, 1.0R, 1.1R, 1.100R}
For Each value in values
Debug.WriteLine(value.ToString("0.##", CultureInfo.CurrentCulture.NumberFormat))
Next
Output will be 1
, 1
, 1.1
and 1.1
, which seems to be what you want (the loss of precision may or may not be what you want).
This is a custom numeric format with digit placeholders, as shown here: Custom Numeric Format Strings.
An alternative are the Standard Numeric Format Strings; especially the general format specifier, which you can use without a precision specifier (which may or may not be what you want).
In response to your edit/comment:
There's no simple single format string you can use, but you could use a simple workaround like this:
value.ToString(If(Math.Abs(value mod 1) < Double.Epsilon, "0", "0.00"), CultureInfo.CurrentCulture.NumberFormat)
Upvotes: 1