How to view formatting numbers in javascript. Currency

Asked

Viewed 122 times

-2

I have a code that takes all the numbers present in input type="text" name="qty" and makes a sum.

If I have two inputs with value 30 and with name="qty", the result of the script would be 30. Only I need that when it returns the result, the numbers are formatted as follows:

100.10
1259.59
1300.30 

That is, before the last two digits appear a semicolon.

My code:

function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('total').value = tot;
}

Would it be possible?

2 answers

5

The question is much confused. In the title you say you want to format "currency", but in your answer you format the number and put "Kg" in front (ie it is not a monetary value).

In addition, you take the value (in your example, it was 2510) and the result is "2.51Kg". Then simply divide by 1000 before formatting the value. But in another answer (which has been deleted) you say that if the value is 3000, you want it to return "30.00" (ie divide by 100). You can’t understand what you need.

Anyway, maybe this helps you. The way you did it is very wrong for several reasons (explain in more detail below). If you want to format numbers, an alternative is to use a NumberFormat, which even supports measurement units:

let nf = Intl.NumberFormat('en',
                           { style: "unit", unit: "kilogram", unitDisplay: "narrow",
                             minimumFractionDigits: 0, maximumFractionDigits: 3});

function findTotal() {
    let tot = 0;
    for (const input of document.getElementsByName('qty')){
        let value = parseInt(input.value);
        if(! isNaN(value))
            tot += value;
    }
    document.getElementById('total').value = nf.format(tot / 1000);
}
<input type="text" name="qty"  value="1255">
<input type="text" name="qty"  value="1255">
<input type="text" name="total" id="total">
<button onclick="findTotal()">teste</button>

Using the filled-in values, the total is 2510 (and note that you don’t need to call parseInt twice: call it only once and use the returned value - include a check to know if the value is a number even, because if something is typed that is not a number, it returns NaN (more about these conversions can be seen here)).

Then I divide the total by 1000 and format using the NumberFormat. I used the unit "kilogram", which already adds the corresponding suffix (see here list of all supported drives). And I use locale en, which uses the dot as separator from the decimal places, which seems to be what you need.

The result is "2.51kg". If you really want the result to have a capital "K", you can use replace('k', 'K') in the result, or remove the unit of measure options and concatenate the "Kg" directly. Remember also that you can use the same options with toLocaleString:

(tot / 1000).toLocaleString('en',
                            { style: "unit", unit: "kilogram", unitDisplay: "narrow",
                              minimumFractionDigits: 0, maximumFractionDigits: 3})
.replace('k', 'K'); // se quiser muito que "kg" seja transformado em "Kg"

// ou, se quiser concatenar o "Kg" manualmente
(tot / 1000).toLocaleString('en', { minimumFractionDigits: 0, maximumFractionDigits: 3}) + "Kg";

I also put the minimum and maximum of decimal places that should be printed, so if the value is 2000, it becomes "2kg", and if it is 2100, it becomes "2.1kg" and so on. You can configure at will, see on documentation all available options.

I’m just not sure if the "kg" (all in lowercase) is standardized or varies depending on the implementation of each browser.


As for your code:

document.getElementById('total').value = tot.toLocaleString('pt-BR')  - 0  + "Kg" 

Although it "works", it is a damned gambiarra (sorry to be so direct, but it is). "en-BR" locale uses the dot as the thousands separator, so the number 2510 becomes the string "2.510". Then, by subtracting zero, this string is converted to number, only that this conversion does not take into account the locale "en-BR" but rather the language conversion rules, in which the point is the decimal separator. Then the string "2.510" is interpreted as the number 2.51 - and when concatenating it with the string "Kg" it is converted to string, which also ignores the rules of the "en-BR" locale and uses the point as decimal separator, resulting in "2.51Kg".

Don’t do this. Use the right tools for each task. First you get the numeric value you want to format (either by dividing by 1000 or 100, or any other calculation you need), and then you format that value.

0

Getting close to what you wanted ( if anyone needs ):

function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('total').value = tot.toLocaleString('pt-BR')  - 0  + "Kg"   ;
}





    
<input type="text" name="qty"  value="1255"   >

<input type="text" name="qty"  value="1255"   >



<input type="text" name="total" id="total"   />


<button onclick="findTotal()"   >teste</button>

Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.