# Rounding problems inside InputField

The community needs to determine if this is behavior is a bug or not. – Mr.Wizard

Consider the following InputField

InputField[Dynamic[h2,
If[# === Null, h2 = h2, h2 = Round[#, 0.001]] &], Number]


The purpose of the second argument of Dynamic is to avoid someone entering a value with more than 3 decimal places (or emptying the field after some value has been assigned).

For example, entering 0.4691 immediately reassigns the InputField to 0.469.

The problem is that entering the number 0.468 renders 0.4680000000000001. I imagine it’s something to do with the representation of 0.468 in binary, etc.

How can I avoid this after rounding action?

EDIT:

After some more testings, I see that it is the Number part that is causing the problem.

InputField[Dynamic[h2], Number]


This works OK:

InputField[Dynamic[h2]]


If you do Do[h2 = i; Pause[0.1], {i, 0.04, 0.08, 0.001}], you can get a good picture of the problem:

How can I avoid this Number side effect?

• Defining h2 in a DynamicModule seems to do the trick, but I don't know if it serves your use, and have no idea why – Rojo Apr 24 '12 at 7:17
• @Rojo I don't think it would serve my use, since I'm defining this variable at the notebook level (I'm even using it inside NotebookDynamicExpression) – P. Fonseca Apr 24 '12 at 7:21
• @Timo I'm on mma 8.0.4 on Windows XP. But I'm glad to know it works fine on other platforms, since it does look like a bug... – P. Fonseca Apr 24 '12 at 7:24
• Works OK in WinXP Mma 8.0.0 – Dr. belisarius Apr 24 '12 at 13:36
• Since this hasn't been fixed (as of 10.3.0), and it has a different behaviour on other platforms, should this be tagged as Bug? – P. Fonseca Nov 16 '15 at 18:57

This seems to work for me, is it what you need?

InputField[Dynamic[h2, If[NumericQ[#], h2 = Round[#, 0.001], h2 = h2] &]]

• Your work around works fine for my specific case, but since it is not a solution for the "bug", since it doesn't cover all the functionality of Number (e.g. assign h2="a" from outside the InputField). I'll wait a little longer to see if there are other solutions (before validating one)... – P. Fonseca Apr 24 '12 at 22:04

Since the type Number won't allow formatted numbers to be displayed, set the accuracy (or precision) of the displayed value to control the number of digits:

InputField[Dynamic[If[h2 == 0, 0., SetAccuracy[h2, 4]], (h2 = Round[#, 0.001]) &], Number]


FullForm[h2]
(*  0.468  *)


It does have the disadvantage that numbers like 0.12 will be displayed as 0.120`. A more complicated program could be written to handle that, if desired.