Why does float subtraction by float give unexpected result?

2

I spent a lot of time to solve this problem on my system. I solved I solved, but at some point it is resulting (the value of the subtraction) = -0.0 and I have to give .replace ('-', '') in order to show the user a positive value and this causes a changeable lapse that is noticeable . All this is occurring due to subtracting 0.1 from 2.8 results in 2.6999999999999997. In my code it is already used .toFixed (1) and anyway it will not, I even used Math.round ().

After all, what is the point of subtracting 0.1 out of 2.8 and resulting in it?

@Edit

Warning to people who "fell" from parachute. This question is not duplicated either has to do with the indicated topic, because my question was something very specific that, just looking at the code in the jsfiddle left in the comments, is that can come a solution to your problem.     

asked by anonymous 30.05.2018 / 05:56

1 answer

2

You have to convert toFixed(1) e to parseFloat() then. You will not be able to use the -= nor the += operator because of the float problem.

Run the snippet and click + in a row until you reach 0 :

var $menosPontoVelocidade = '#menos-ponto',
	$addPontoVelocidade = '#add-ponto',
	$velocidadeId = '#velocidade',
	$podeAdicionarHabilidades = true,
	$podeRetirarHabilidades = false,
	$podeRetirarHabilidadeVelocidade = false,
	$pontosDistribuirHabilidades = 2,
	$pontosDistribuirHabilidadesId = '#pontos-distribuir';


$(function($) {
	$($menosPontoVelocidade).on('click', function() {
			if ($podeRetirarHabilidades && $podeRetirarHabilidadeVelocidade) {
				retirar_pontos_habilidades($velocidadeId);
			}
		});
		
	$($addPontoVelocidade).on('click', function() {
		if ($podeAdicionarHabilidades) {
			adicionar_pontos_habilidades($velocidadeId);
		}
	});
	
	
	function retirar_pontos_habilidades($inputId) {
		$pontosDistribuirHabilidades += 0.1;
		$($pontosDistribuirHabilidadesId).text($pontosDistribuirHabilidades.toFixed(1));
		var $str = (parseFloat($($inputId).val()) - 0.1).toFixed(1);
		$($inputId).val($str);
	}

function adicionar_pontos_habilidades($inputId) {
		$pontosDistribuirHabilidades = parseFloat(($pontosDistribuirHabilidades-0.1).toFixed(1));
		$($pontosDistribuirHabilidadesId).text($pontosDistribuirHabilidades.toFixed(1));
		var $str = (parseFloat($($inputId).val()) + 0.1).toFixed(1);
		$($inputId).val($str);
	}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><spanid="menos-ponto"> - </span>
<input type="text" size="5" id="velocidade" disabled value="0.0" />
<span id="add-ponto"> + </span>
<p id="pontos-distribuir">2.0</p>
    
30.05.2018 / 08:27