Question: I am trying to interface with a machine over RS232 and the machine requires all input to have a decimal separator or else it assumes the decimal position. E.G. If I send `25` it will interpret that as `0.025`, but `25.000` or `25.` will be received properly as `25.000` 

I tried [`Math.Round`](https://msdn.microsoft.com/en-us/library/System.Math.Round(v=VS.110).aspx) but for whole number values it doesn't include the trailing zeros.

So, if I have

```
float a = 90;
float b = cos(24);
comPort.WriteLine("G01 A" + a + " B" + b);

```

What do I need to add so that it forces 3 decimals places? I'm not concerned about how it's rounded nor if it truncated.

Answer: 
Use string formatting. All the info you need is on the following MSDN pages: 

* [Standard Numeric Format Strings](https://msdn.microsoft.com/en-us/library/dwhawy9k.aspx) for the most common formats
* [Custom Numeric Format Strings](https://msdn.microsoft.com/en-us/library/0c899ak8.aspx) if you require something else

```
float a = 90;
float b = cos(24);
comPort.WriteLine("G01 A{0:F3} B{1:F3}", a, b);

```

`F3` means fixed point with 3 digits of precision after the decimal separator.

This works if `comPort` is something like a `TextWriter`, because this class has a [`WriteLine` overload](https://msdn.microsoft.com/en-us/library/60scc1f1.aspx) which supports formatting. If you're using `SerialPort` directly, you don't get that overload, and you have to put `string.Format` explicitly in there:

```
comPort.WriteLine(string.Format("G01 A{0:F3} B{1:F3}", a, b));

```

Some equivalent ways to write the same thing:

```
comPort.WriteLine("G01 A{0:0.000} B{1:0.000}", a, b);

```

Or in C#6:

```
comPort.WriteLine($"G01 A{a:F3} B{b:F3}");

```

That one will get translated to the following by the compiler:

```
comPort.WriteLine(string.Format("G01 A{0:F3} B{1:F3}", a, b));

```
Instead of using concatenation, use String.Format

```
comPort.WriteLine(String.Format("G01 A{0:F3} B{1:F3}", a, b));

```