Problem when calculating percentage using parseFloat and toFixed

1

I want to do something very simple, but simple as it is, I can not. I have an input that receives the cost value, an input that calculates and shows the profit margin in% and an input that receives the sales price.

Thequestionisasfollows,thewayIgotittoday,thecalculationisdonecorrectlyonlyuptothevalue($999.99),whenitreachesthethousands,thecalculationofawrongvalue,forexample:

Andaboveall,thecalculationignoresthedecimalplaces.IfIputasalepricebeing$199.00ofthesameprofitmarginasIput$199.99,thatis,199.90heseesas199and199.00healsoseesas199.ItseemstobesomethingsosimpleandIcannotdoit.

CodeIcurrentlyhave:

varprecoVenda=parseFloat($("input[name='iptPrcVendaProdutoEditar']").val());             
var precoCusto = parseFloat($("input[name='iptPrcCustoProdutoEditar']").val());
var margemLucro = parseFloat((((precoVenda - precoCusto)/precoCusto)*100)).toFixed(2);
$("input[name='iptMargemLucroProdutoEditar']").val(margemLucro.replace('.',','));
    
asked by anonymous 23.06.2018 / 15:45

2 answers

0

You can also use split and join to convert the fields.

I've put snippet to exemplify.

function calculo() {

var pv = parseFloat($("input[name='iptPrcVendaProdutoEditar']").val().split('.').join('').split(',').join('.'));

var pc = parseFloat($("input[name='iptPrcCustoProdutoEditar']").val().split('.').join('').split(',').join('.'));

$("input[name='iptMargemLucroProdutoEditar']").val(

(!isNaN(pv) && !isNaN(pc) ?

((pv - pc) / pc * 100).toFixed(2) + '%' :

'')

);

};

$('input').not(':last').on('keyup', function() { calculo(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Preçovenda:<inputtype="text" name="iptPrcVendaProdutoEditar" /><br /><br />
Preço custo: <input type="text" name="iptPrcCustoProdutoEditar" /><br /><br />
Margem lucro: <input type="text" name="iptMargemLucroProdutoEditar" readonly="readonly" />
    
26.06.2018 / 22:29
1

function to change characters

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

how to call function

replaceAll('20,00',',','.');

another simple way

variavel.replace(/,/g, '.');
    
23.06.2018 / 16:28