Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

This works "badly":

InputField[Dynamic[h2], Number]

This works OK:

InputField[Dynamic[h2]]

enter image description here

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:

enter image description here

How can I avoid this Number side effect?

share|improve this question
    
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 –  belisarius Apr 24 '12 at 13:36

1 Answer 1

up vote 4 down vote accepted

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

InputField[Dynamic[h2, If[NumericQ[#], h2 = Round[#, 0.001], h2 = h2] &]]
share|improve this answer
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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