Group Abstract Group Abstract

Message Boards Message Boards

0
|
12.1K 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
Attachments:
POSTED BY: Neil Singer
Posted 9 years ago
POSTED BY: Mark Alford

Mark,

Did this work for you?

POSTED BY: Neil Singer

Mark,

This is actually very hard -- there is no simple way to do it. I posted a similar question here in my post but got no replies and even had tech support look at it and had little resolution. I came up with an approach that works by wrapping the numbers in a temporary function and after turning everything into CForm, doing a string replace. Here is some sample code. mapReplace goes through an expression and replaces the Real numbers with a dummy function acf[ paddedform ]. You can edit the paddedForm below to get your desired format.

mapReplace[exp_] := 
 MapAt[acf[
    ToString[
     PaddedForm[#, {8, 3}, 
      NumberFormat -> (Row[{#1, If[#3 != "", "e", ""], #3}] &)]]] &, 
  exp, Position[exp, _Real]]

after this you do a stringReplace to clean it all up:

CNumberReformat[expr_] := 
 StringReplace[ ToString[mapReplace[expr], CForm], 
  Shortest["acf(\"" ~~ x__ ~~ "\")"] :> "(" <> x <> ")"]

To use it:

equation = 25.32032 - 4.55 x + 16.0006 z + 2 y + 234.2341*^8
CNumberReformat[equation]

to get

2y + z( 16.001) + ( 2.342e10) + x*( -4.550)

I hope this helps.

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