2

Apologies for the common question, but as I tried to find a direct answer to my problem on the forum it don't seem I found it.

See, I have an text input (id = avt_ht) in Javascript where I put a number received in form of a string, like this :

1 200,00

I take this value, convert it into a float with something like this :

var ht_txt = $("#avt_ht").val();
ht_txt = ht_txt.replace(' ', '');
var ht_val = parseFloat(ht_txt);

Then, I use it to make some calculation, like

var ttc_val = ht_val + tva_val;

Now my point is I want to convert these numbers again in order to give them the same format at my beginning. I tried somethings like this :

var ttc_txt = ttc_val.toLocaleString();

But It is not appropriate. I don't really know if I can use NumberFormat in JS like in PHP (it seems not to be the same way of using it), if I have to use a regex, etc...

Does someone knows how to do it ?

3
  • You need also replace comma with a dot for parseFloat to work properly. Commented Mar 3, 2016 at 10:42
  • What jcubic is saying is that in parseFloat('1200,00') only the '1200' part of the number is used, so strings like '1200,12' will not keep their decimal part, it must be '1200.12'. Commented Mar 3, 2016 at 10:44
  • Thanks, guys ! I help to have the cents modificated as well. But do you know why, if I try to modificate it again, It does not execute my ht_txt.replace(' ', ''); ? I wonder if it was something to do with the fact that, if I change a unit, it doesn't show ",00" Commented Mar 3, 2016 at 10:52

1 Answer 1

2

Use toFixed() method of float:

var ttc_txt = parseFloat(ttc_val).toFixed(2);

Returns something like "123.00" You can use it as string. If you need a strict type string, just add +"" to expression:

var ttc_txt = parseFloat(ttc_val).toFixed(2)+"";
Sign up to request clarification or add additional context in comments.

1 Comment

Great ! I just had to change my toLocaleString by your .toFixed(2)+""; and now my numbers don't have calculations troubles anymore. I just need to formate a little here and that. Thanks, Dmitry !!

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.