Convert String With Dot or Comma to Float Number

How can I convert a string with dot and comma into a float in Python

Just remove the , with replace():

float("123,456.908".replace(',',''))

Convert String with Dot or Comma as decimal separator to number in JavaScript

Do a replace first:

parseFloat(str.replace(',','.').replace(' ',''))

How to convert floating point decimal separator from dot to comma in Javascript

parseFloat("2,83") will return 2 because , is not recognized as decimal separator, while . is.

If you want to round the number to 2 decimal places just use parseFloat(discval.toFixed(2)) or Math.round(discval * 100) / 100;

If you need this jut for display purposes, then leave it as a string with a comma. You can also use Number.toLocaleString() to format numbers for display purposes. But you won't be able to use it in further calculations.

BTW .toFixed() returns a string, so no need to use .toString() after that.

Converting a number with comma as decimal point to float

Using str_replace() to remove the dots is not overkill.

$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));

// At this point, $number is a "natural" float.
print $number;

This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.



Related Topics



Leave a reply



Submit