Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics AX (Archived)

Format real number as a string without trailing zeros

Posted on by 203

Hi

How can I best convert a real number such as 16.00000000000000 into a string "16"?

I can use num2str but that doesnt remove the zeros.  And I can loop through the string and remove the zeros and then remove the decimal point as well, but wondered if there was a more elegant solution?

Thanks in advance

*This post is locked for comments

  • cjohnson300 Profile Picture
    cjohnson300 203 on at
    RE: Format real number as a string without trailing zeros

    perfect - thank you!

  • Verified answer
    Martin Dráb Profile Picture
    Martin Dráb 230,235 Most Valuable Professional on at
    RE: Format real number as a string without trailing zeros

    Oh, sorry, now I see I didn't give you the right answer.

    I would do this:

    str s = System.String::Format("{0:G29}", number);

    It returns 15 and 16.125 in your two cases (I've tested it in D365FO).

    By the way, -1 in num2str() means using defaults.

  • cjohnson300 Profile Picture
    cjohnson300 203 on at
    RE: Format real number as a string without trailing zeros

    What do the -1s indicate?!  It's not in the Microsoft TechNet definition!  And I just tried it and it returned 15.00 for 15.000000000000000

  • Martin Dráb Profile Picture
    Martin Dráb 230,235 Most Valuable Professional on at
    RE: Format real number as a string without trailing zeros

    In that case, num2str() is exactly what you need For example: num2Str(16.1250000000000000, -1, -1, -1, -1).

  • cjohnson300 Profile Picture
    cjohnson300 203 on at
    RE: Format real number as a string without trailing zeros

    Thanks Martin

    And if the "real" was 16.1250000000000000, would your solutions still hold?  I would like to see 16.125

  • Martin Dráb Profile Picture
    Martin Dráb 230,235 Most Valuable Professional on at
    RE: Format real number as a string without trailing zeros

    Setting the third argument of num2str() should do the trick.

    You could also convert the real number to int and use int2str().

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans