Wolfram Community,
I have some expressions with floating point numbers. Ultimately I need them in CForm but I am having difficulty in getting the numbers to format correctly. (It seems easy but it is not).
I need to limit the number of significant digits -- I can't have more than 14 digits in my numbers. I tried:
numberReformat[exp_]:= MapAt[Round[#,N[1*^-8]]&,exp,Position[exp,_Real]]
This picks off all the real numbers in an expression and rounds all of the real numbers to 8 decimal places past the decimal, Numbers such as 1234.123456789012345
numberReformat[1234.123456789012345] // CForm
will round to 1234.12345679
This fails to work beyond 10 decimal places -- it limits everything to 10 places. for example:
numberReformat[exp_]:= MapAt[Round[#,N[1*^-14]]&,exp,Position[exp,_Real]]
still limits to 10 decimal places even thought it is set to 14.
The second problem is that numbers with exponents will have too many digits:
numberReformat[9.123456789012345*^12] // CForm
produces:
9.123456789012346e12
Which has too many digits (e12 part is fine but there are 17 digits in the number.
I also tried NumberForm but this seems incompatible with CForm:
NumberForm[9.123456789012345*^12, 14]
produces what I want:
9.1234567890123*10^(12)
but when I apply CForm to the expression it becomes
NumberForm(9.123456789012346e12,14)
instead of the number.
Does anyone have a simple way to round numbers to say 12 or 14 significant digits (similar to NumberForm) for numbers mixed in a mathematical expression so that when it converts to CForm it stays that way?
Thank you.