6
$\begingroup$

I've read the available documentation but I still haven't found an NumberForm -> Integer function yet. No result in this site's search, either.

Does it exist?

I should mention: there are no decimals in my numbers. They are all integers, which makes me wonder why MMA bothers to fiddle with them at all. Numbers like 84039 get transformed to 84039.0, and 8048511 to 8.048511*10^6


The problem is I'm importing an XLS file that should contain only strings - the fields are set to Text in Excel - but Mathematica has its way when using Import and outputs a list containing multiple different number formats. Preferably, everything imported by Mathematica would be kept as string, and not converted to Real or ScientificForm.

Exporting to CSV and reopening with ReadList also hasn't worked well.

$\endgroup$
1

2 Answers 2

10
$\begingroup$

A simple solution is to use Rationalize on the result. If your original data is all integers, but with the head Real (e.g. {1., 2., 3.}) then they'll have the head Integer now (i.e., {1, 2, 3}).

$\endgroup$
2
  • $\begingroup$ Why isn't Rationalize in the documentation (tutorials or how-to's)? That's surprising, but thanks :) $\endgroup$
    – CHM
    Jul 9, 2012 at 22:48
  • $\begingroup$ @CHM Probably because they wanted to keep the tutorial aimed towards the general case. For example, if you use Rationalize on a list like {1., 1.5, 2.}, then you'll end up with {1, 3/2, 2}, which may or may not be what you want. In such cases, you might look at this question for a solution $\endgroup$
    – rm -rf
    Jul 10, 2012 at 0:33
4
$\begingroup$

This is just one of a range of problems in importing data from Excel (don't let me count the ways).... I wasn't aware of Rationalize, but here's a Rule that can be applied upon import to round numeric data:

ExcelImportRule = (x_ /; (NumericQ[x] && (Abs[x - Round[x]] < $MachineEpsilon)) :> Round[x]) 
$\endgroup$
1
  • $\begingroup$ I had the exact same question, students sending in answers to test questions in an Excel file. Very important that some be integers and some decimals. They would enter them in Excel, but on import, Mathematica changed them all to reals. The above rule was EXACTLY what I needed and solved a big headache in my test grading workflow... thank you! $\endgroup$ Feb 7, 2014 at 11:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.