If they're meant to be separate values, try this:
var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])
If they're meant to be a single value (like in French, where one-half is written 0,5)
var value = parseFloat("554,20".replace(",", "."));
Have you ever tried to do this? :p
var str = '3.8';ie
alert( +(str) + 0.2 );
+(string) will cast string into float.
Handy!
So in order to solve your problem, you can do something like this:
var floatValue = +(str.replace(/,/,'.'));
HTML:
<div id="box">
<p> Valor: <input id="valor"> </p>
<p> Taxa: <input id="taxa"> </p>
<p> Imposto: <input id="imposto"> </p>
<p> Envio: <input id="envio"> </p>
<p> Taxa adicional: <input id="taxa_adicional"> </p>
<p> Subtotal: <span id="subtotal">0</span> </p>
<p> Total: <span id="total">0</span> </p>
</div>
JavaScript:
var options = {
format: '#,###.00',
locale: 'br'
},
inputs = $( 'input:text', '#box' ).get(),
input_adicional = $( '#taxa_adicional' )[0],
input_total = $( '#total' )[0],
input_subtotal = $( '#subtotal' )[0];
and then:
$( inputs ).add( [ input_total, input_subtotal ] ).format( options );
$( inputs ).
blur( function () {
var total = 0,
subtotal = 0;
// on blur, format the field
$( this ).format( options );
// calculate the sum of all input fields
$( inputs ).each( function () {
total += +$( this ).parse( options );
});
// subtotal doesn't include the "additional" field
subtotal = total - $( input_adicional ).parse( options );
// populate the SPAN's with the sums and format the nubmers
$( input_subtotal ).text( subtotal ).format( options );
$( input_total ).text( total ).format( options );
}).
focus( function () {
// if the field contains the value 0, empty it
if ( +$( this ).parse( options ) === 0 ) {
this.value = '';
}
});
Live demo: http://jsfiddle.net/U9V6x/
When you're calculating your subtotal, you are calling parseFloat() on a series of strings, not the variables themselves. The line should be:
var subtotal = parseFloat(val) + parseFloat(tax) + parseFloat(imp) + parseFloat(env);
parseInt("1.0") will be same as parseInt("1.1") parseFloat("1.0") will be different to parseFloat("1.1")
These functions are basically to parse string data to the relative format so according to the conditions we can use them
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
The parseFloat() function parses an argument and returns a floating point number.
console.log(parseInt("1.11"))
console.log(parseFloat("1.11"))
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
If you need performance (like in games):
Math.round(number * 100) / 100
It's about 100 times as fast as parseFloat(number.toFixed(2))
http://jsperf.com/parsefloat-tofixed-vs-math-round
EDIT:
https://jsperf.app/kowulu