6

This is what works as expected:

This parseFloat(newValue).toLocaleString("de-DE", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) will result in a String: "34.886,55"

This does not work as expected:

For parseFloat("34.886,55") I get a Number, but I lost everything after the comma: 34.886.

How can I fix this problem ?

user7425470
  • 735
  • 1
  • 6
  • 13
  • parseFloat("34886.55") the commas is invalid, so the parse stop right before it. Also the full stop is the decimal separator. – Salketer Sep 18 '17 at 14:21
  • Possible duplicate of [Javascript parse float is ignoring the decimals after my comma](https://stackoverflow.com/questions/7571553/javascript-parse-float-is-ignoring-the-decimals-after-my-comma) – evolutionxbox Sep 18 '17 at 14:23
  • Why not remove the comma before processing [sample fiddle](https://jsfiddle.net/f0qwkxhn/) – Naren Murali Sep 18 '17 at 14:25
  • @NarenMurali the comma is decimal separator in de-DE, while dot is thousand separator. Removing it would not help... – Salketer Sep 18 '17 at 14:27
  • @Salketer Ok got it, didn't know that! Thanks! – Naren Murali Sep 18 '17 at 14:28

2 Answers2

0

I wrote this simple function for doing locale based parseFloat, to the best of my knowledge, the assumptions for this function are.

  1. The decimal operator will come once.
  2. So split it at the decimal("," in our case) to get two elements in an array.
  3. Then remove the thousands separator("." in our case) for each of the elements in the array.
  4. Then joinback the array with the decimal separator ("." in our case)
  5. finally return the parseFloat value of this joined number!

var str = "34.886,55"
console.log("before: ", str);
str = localeParseFloat(str, ",", ".");
console.log("resulting floating value from the function: ", str);

function localeParseFloat(str, decimalChar, separatorChar){
var out = [];
str.split(",").map(function(x){
    x = x.replace(".", "");
  out.push(x);
})
out = out.join(".");
return parseFloat(out);
}
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
Vega
  • 27,856
  • 27
  • 95
  • 103
Naren Murali
  • 19,250
  • 3
  • 27
  • 54
-2

Here's a brief example of the number parsing... Commas are not valid in numbers, only the full stop represents the decimal separator. If it is encountered, the string conversion stop, as you can see on the second log. Also check the third log, I've added a check for the value to be true if it's lower than 100, making it more obvious that you are not playing with thousand separator but really decimal separator.

console.log(parseFloat("34.886.55"));
console.log(parseFloat("34,886.55"));
console.log(parseFloat("34.886,55"), parseFloat("34.886,55") < 100);
Salketer
  • 14,263
  • 2
  • 30
  • 58