SBX - Search With Button

SBX - Forum Post Title

Format real number as a string without trailing zeros

Microsoft Dynamics AX Forum

cjohnson300 asked a question on 14 Sep 2018 6:18 AM
My Badges

Question Status

Verified

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

Reply
Martin Dráb responded on 14 Sep 2018 6:26 AM

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

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

Reply
cjohnson300 responded on 14 Sep 2018 6:50 AM
My Badges

Thanks Martin

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

Reply
Martin Dráb responded on 14 Sep 2018 7:43 AM

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

Reply
cjohnson300 responded on 14 Sep 2018 7:57 AM
My Badges

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

Reply
Martin Dráb responded on 14 Sep 2018 8:21 AM
Verified Answer

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.

Reply
cjohnson300 responded on 14 Sep 2018 8:47 AM
My Badges

perfect - thank you!

Reply
Martin Dráb responded on 14 Sep 2018 8:21 AM
Verified Answer

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.

Reply

SBX - Two Col Forum

SBX - Migrated JS