6

I have already tried the following:

discval = 2.833423
discval = discval.toFixed(2).toString().replace("." , ",");
discval = parseFloat(discval);

The output is 2 and not 2,83

Any idea?

0

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup, you really need to know why you want to change the dot with a comma. Anything else than display purposes is probably a wrong approach.
4

From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.

If the first character cannot be converted to a number, parseFloat returns NaN.

, is not an expected character so the number is truncated to that.

It's not possible to change the representation of floating point numbers in Javascript, you will need to treat your number as a string if you want to separate decimals with a comma instead of dot.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.