Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. String.Format-ting floating point numbers, how?

String.Format-ting floating point numbers, how?

Scheduled Pinned Locked Moved C#
tutorialquestion
3 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I Offline
    I Offline
    iliyang
    wrote on last edited by
    #1

    I want to format a floating point number with accuracy 2 digits after the point, but if the number is round, to show it more friendly. For example: if the number is 2.3, show 2.3 and not 2.30 if it's 3, show 3 and not 3.00 and if the number is 4.12345, show 4.12 What' the formatting string that I can achieve this with? Thanks in advance ;)

    S 1 Reply Last reply
    0
    • I iliyang

      I want to format a floating point number with accuracy 2 digits after the point, but if the number is round, to show it more friendly. For example: if the number is 2.3, show 2.3 and not 2.30 if it's 3, show 3 and not 3.00 and if the number is 4.12345, show 4.12 What' the formatting string that I can achieve this with? Thanks in advance ;)

      S Offline
      S Offline
      Seraphin
      wrote on last edited by
      #2

      float number = 4.12345; string result = String.Format("{0:00}", Math.Round(number,2));

      I 1 Reply Last reply
      0
      • S Seraphin

        float number = 4.12345; string result = String.Format("{0:00}", Math.Round(number,2));

        I Offline
        I Offline
        iliyang
        wrote on last edited by
        #3

        Ahha! Works, but with formatting string "{0}" is better. Thanks a lot, seems that the Round trick is the keystone here ;)

        1 Reply Last reply
        0
        Reply
        • Reply as topic
        Log in to reply
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes


        • Login

        • Don't have an account? Register

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • World
        • Users
        • Groups