I am trying to round/ only print out floating numbers to a certain length no matter what the value is (I have a document that it needs to fit properly in). I am using powershell but I haven't found anything useful.
There can be a max of 6 digits if you include a decimal point.
Here is what i am looking for below.
17.12356 => 17.1236
189.12345 => 189.123
12345 => 12345.0
122909808 => 122909 ( I haven't though of a proper way to show this case, suggestions would be helpful)
The G format specifier will truncate your number to a specified number of significant digits, but without any forward zero padding of small numbers. The following code gives an example of the kind of thing you might get for various types of numbers and with 5 significant digits (6 chars wide allowing for the decimal point). Note that for very large or small numbers you get 'scientific' notation, which will obviously be wider than 6 chars. For these cases you would need to find the large numbers and move the 'E' at least 4 spaces to the left , but then you lose a lot of detail. Up to you what you want to sacrifice, really.
PS > @(12345.678,123.45678,12345678,12345,123.4, 0.00123456) |%{"{0:G6}" -f $_} | %{if ($_.Leng
th -le7) {$_} else {$_.Substring(0,7)} }
12345.7
123.457
1.23457
12345
123.4
0.00123