Skip to main content

output formatting - How to change the color of specified digits in a number?


I've been playing with numerical approximations for irrational numbers, and would find it convenient to be able to highlight where these approximations deviate from the known correct answers. For example, it would be nice to be able to output a number that looks like


not quite Pi


where most of the digits have the default Output format, but after a specified number of digits, a different format (bold and red in this example) applies.


What would be the most elegant way to accomplish this?



Answer



Another approach:


mark[s_, where_] := With[{n = ToString@s},
Row@{StringDrop[n, -where], Style[StringTake[n, -where], Red]}]


Let's say you want to mark last 3 digits:


mark[N[Pi, 45], 3]



And a little bit more general approach:


mark[s_, w_] := With[{n = ToString@s}, 
Row@MapAt[Style[#, Bold, Red] &, Characters[n], {w}]]

it can work with Span:




enter image description here


enter image description here



Just for fun, an extension:


mark[number_, spec : {{_, _} ..}] := With[{n = Characters@ToString@number},
Fold[
Function[{x, y}, MapAt[Style[#, y[[ 1]]] &, x, y[[ 2]]]],
n,
spec]] // Row



enter image description here



Comments