Rationalization of numerical output

Consider:

Grid@Partition [ Text[Style[ToString[Range[0, 180, 22.5][[#]]] <> "\[Degree]", Bold, 16, GrayLevel[(8 - #)/10]]] & /@ Range[8], 2, 1] 

enter image description here

How can I get rid of a dot after integers?

+7
source share
5 answers

If a number becomes an integer when rationalized, use an integer; otherwise stick to the original number. This is achieved by a simple function, f[x] :

 f[x_] := If[IntegerQ[n = Rationalize[x]], n, x] 

Testing...

 f[67.5] f[0.] f[45.] (* Out *) 67.5 0 45 

You cannot just Rationalize all the values ​​as shown below:

rationalize

To find out how this works in your case, just paste (f/@) into your code to reformat the values ​​output from Range :

 Grid@Partition [ Text[Style[ ToString[(f/@ Range[0, 180, 22.5])[[#]]] <> "\[Degree]", Bold, 16, GrayLevel[(8 - #)/10]]] & /@ Range[8], 2, 1] 

So,

temps

+10
source

Although the original question does not contain numbers with exponents, it would be safer to use NumberForm as follows:

 trimPoint[n_] := NumberForm[n, NumberFormat -> ( DisplayForm@ RowBox[Join[{StringTrim[#1, RegularExpression["\\.$"]]}, If[#3 != "", { "\[Times]", SuperscriptBox[#2, #3]}, {}]] ] &)] 

Then you only need to change the source code by inserting // trimPoint as follows:

 Grid@Partition [ Text[Style[ ToString[Range[0, 180, 22.5][[#]] // trimPoint] <> "\[Degree]", Bold, 16, GrayLevel[(8 - #)/10]]] & /@ Range[8], 2, 1] 
+9
source

Another possibility is not to generate them in the first place.

 If[IntegerQ[#], #, N@ #] & /@ Range[0, 180, 45/2] 

gives

{0, 22.5, 45, 67.5, 90, 112.5, 135, 157.5, 180}

+6
source

In general, you should use Rationalize .

 Rationalize@10. Out[1] = 10 

However, in your case, you should not just use Rationalize , since you do not want to work with some elements. Here is a simple approach that will do what you want.

 list = Range[0, 180, 22.5] /. (x_ /; FractionalPart@x == 0.) -> IntegerPart@x Grid@Partition [ Text[Style[ToString[list[[#]]] <> "\[Degree]", Bold, 16, GrayLevel[(8 - #)/10]]] & /@ Range[8], 2, 1] 

enter image description here

The code above generates the same list as yours, and then conditionally replaces those elements that have a FractionalPart equal to 0. (for example, 10. ), with IntegerPart (for example, 10 ).

+5
source

Another option is to remove any trailing "." using StringTrim :

 Grid@Partition [ Text[Style[ StringTrim[ToString[Range[0, 180, 22.5][[#]]], "."] <> "\[Degree]", Bold, 16, GrayLevel[(8 - #)/10]]] & /@ Range[8], 2, 1] 
+4
source

All Articles