Group Abstract Group Abstract

Message Boards Message Boards

0
|
11.2K Views
|
4 Replies
|
5 Total Likes
View groups...
Share
Share this post:

Control the number of digits in CForm output?

Posted 9 years ago

I would like to print out numbers in C form with exactly 3 digits after the decimal point. E.g.

  • 1.23456*^8 -> 1.234e8
  • 1.0*^8 -> 1.000e8

I thought I could do something like

PaddedForm[CForm[1.23456*^8],{8,3}]

but that didn't work.

CForm[SetPrecision[1.0*^8 ,4]] 

also fails to give 3 digits after the decimal point.

POSTED BY: Mark Alford
4 Replies

If you define the format function as follows:

format[x_] := 
 ToString[PaddedForm[x, {4, 3}, 
   NumberFormat -> (Row[{#1, If[#3 != "", "e", ""], #3}] &), 
   ExponentFunction -> (# &)]]

It will do the formatting you want. I added the ExponentFunction option. By always returning its argument (#,&), you ALWAYS get exponential notation. (If you want to limit exponential notation to a range of exponents, you can change the function -- see the documentation examples). You can add this format to what I posted above by doing this:

mapReplace[exp_] := MapAt[acf[format[#]] &, exp, Position[exp, _Real]]

You can get almost any formatting you want this way but it requires studying the PaddedForm options carefully.

If you really want C formatting, you can very easily call a C sprintf external and print your numbers (and use the code I posted above to apply it to all the numbers in your equations). I have done this in the past (for similar reasons) and I post my code here so you can use it. See the .nb file for instructions. You will need the c file (I had to use a .txt extension to be able to post it). and a .tm file (same name change required). The command I put in the notebook is for a Mac but you can do the same on the PC by looking at the WSTP documentation (for Mac) (for windows).

Using this external function you will get the full functionality of C sprintf for formatting a single number. If you want a more general sprintf function you can edit my C code and tm file to get what you need.

I hope this helps.

Attachments:
POSTED BY: Neil Singer
Posted 8 years ago
POSTED BY: Mark Alford

Mark,

Did this work for you?

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