Message Boards Message Boards

0
|
3687 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

[?] Does NumberPadding work in NumberForm?

Posted 7 years ago

Dear Community,

I would like to produce output of a two-digit number like 7.2 as 7.200, a three-digit number like 27.2 as 27.20, and a four-digit number like 127.2 as 127.2. I tried

NumberForm[7.2, 4, NumberPadding -> {"", "0"}]

but it produced verbatim 7.2, not 7.200. Even though the following would produce what I want for 27.2

NumberForm[27.2, {4, 2}, NumberPadding -> {"", "0"}]

it wouldn't produce what I want for 7.2 or 127.2.

Any suggestion for this petty question is much appreciated!

POSTED BY: Chi-Hsiang Wang
2 Replies

You can define your format (the {4,2}) inside the NumberForm expression as a function:

formatter[x_] := Module[{exp = Floor[Log10[x]] + 1}, {4, 4 - exp}]

And use it in NumberForm:

myNumberForm[x_] := 
 NumberForm[x, formatter[x], NumberPadding -> {"", "0"}]

To get

myNumberForm[7.2]
7.200
myNumberForm[27.2]
27.20
myNumberForm[127.2]
127.2

Also, my response to this link may help you. link to CForm discussion. You can even use sprintf formatting.

I hope this helps.

Regards

Neil

POSTED BY: Neil Singer

Many thanks, Neil, this is exactly what I'm looking for and what I intuitively expected of the format that NumberForm would have supported! I think Wolfram should make it a built-in capability.

Will also have a closer read of the link you provided.

Much appreciated and regards,

Chi-Hsiang

POSTED BY: Chi-Hsiang Wang
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract