Format double value to fixed length string

  • 12 years ago

    Hi all,

    I have a question on formating double values to string...I know how to do it for fixed length of decimals but I cannot find a way how to format it so that a value will always have 4 numbers and depending on that value how many decimals there will be.

     

    For example i have a value 125.46458645 which I want to format to 125.5

    and value 12.54654747654 which I want to format to 12.55

    and value 1.254656555 to 1.255

    Thanks

    Best regards

    Grega 



     

  • 12 years ago

    There are quite a few ways to achieve what you want, although you will have to type your result back to Decimal/Double afterwards. The problem is you are formatting the number, which can only be done via string manipulation. I'm sure there is a more direct approach, but I couldn't be bothered reading about Number Styles. Anyhoo.

    Use String.Format("{0:F3}", 124.5)

    Or MyDecimalValue.ToString("##.####")

    The first method uses format specifiers, and there are many types to coincide with various formats, but if you just take the method, F3 = 3 decimal places.

    The second method uses placeholders to format the text, and you just use the necessary amount of string[#] to act as a placeholder for the required number format. Don't forget to type the result back to Decimal/Double.

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!' but 'That's funny...'” - Isaac Asimov