14,486,801 members
Rate this:
See more:
I am trying to use the ToString method to format a number. The number can be a whole number or a decimal number.

When the number is a whole number, I want the number to include just the trailing decimal point and nothing after that. If the number is not a whole number, then I want to format it with up to 4 starting and 4 trailing digits.

For example:

20 -> 20.
10 -> 10.

10.25114 -> 10.2511
100.156 -> 100.156

What I have tried:

I have been using the following:

```Dim Output as String
Dim Input as decimal = 20

Output = Input.ToString("####.####")```

This, however still leaves me with just the 20 and no trailing decimal point.

If I change the first trailing digit in the format to a zero then it will return 20.0

`Output = Input.ToString("####.0###")`

I know I could just strip off the single trailing zero after doing the above format, however, I am trying to do it all with just the ToString method. Is this possible or not?
Posted
Updated 23-Mar-20 9:18am
Comments
ZurdoDev 23-Mar-20 14:32pm

I've never seen a format that will leave a decimal point with nothing after it, so my guess is you'll have to write your own method or function.

Rate this:

## Solution 1

There is no standard method to format a "trailing decimal point" without a digit of some form after it - but the simplest way to do it is just format it with a zero, and use Trim to remove leading and trailing zeros:
`Output = Input.ToString("####.0###").Trim("0")`
v2
Comments
theskiguy 24-Mar-20 7:26am

That is similar to what I was thinking I would have to do. I do like your solution as it is a nice way to do it in a single line. Thanks,
OriginalGriff 24-Mar-20 7:44am

You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 Maciej Los 210 OriginalGriff 210 Richard Deeming 200 Richard MacCutchan 190 steveb 110
 OriginalGriff 5,728 Richard MacCutchan 3,067 Richard Deeming 2,972 phil.o 2,911 Maciej Los 2,373

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100