0

I have a getter and setter function in a Vue component that ideally would allow the user to type in percentages as whole numbers and my application use them as decimals. Here is the getter/setter:

theValue:{
  //display whole numbers to the user
  get(){
    if(this.value < 1){
      return this.value * 100
    }
    return this.value
  },
  // set the decimal into the application
  set(update){
    this.$emit("input", val/100 );
  }
}

The setter works as expected, however, when the getter receives the value again I have some unexpected consequences.

When you type in the input 7 it displays 7.0000000001 on the input. The application sees .07 just fine. When you type 111 in the input it displays 1.11 instantly.

I can duplicate the issue in the console, what would be a practical way about going about remedying this.

Caveats: These are reusable components and some values in the application can have up to 7 leading zeros for valid values. Using toFixed() is not going to work as there needs to be flexibility in this component for these fields. In theory, I could write 2 different components, one for simple numbers to the hundredth and another for past that. I'm wondering if there are any ideas to do this gracefully.

illcrx
  • 774
  • 1
  • 12
  • 32
  • https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Jaromanda X Dec 03 '19 at 23:28
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – th3n3wguy Dec 04 '19 at 00:25
  • This ADDRESSES the issue but doesnt not specifically give an answer. I find it kind of funny how in all of Javascript no one has actually figured out how to solve this problem. I have figured out a workaround however. – illcrx Dec 04 '19 at 03:54
  • get(){ if(this.value < 1){ return Number(Math.abs(this.value * 100).toFixed(2)); } – illcrx Dec 04 '19 at 03:54

0 Answers0