Javascript format a number asin C# - javascript

I have a number which currently is 1,657,108,700 and growing. However I wish for it to show as
1,657,108k
Does javascript or html have a build in function to do this?
The value is being set throu javascript to a span field in html.
[edit]
From the comment I got my method as far as:
var start = '1,657,108,700';
start = (start / 1000).toFixed(0);
var finish = '';
while (start.length > 3)
{
finish = ','.concat(start.substring(start.length - 3, 3), finish);
start = start.substring(0, start.length - 3);
};
finish = start + finish + "k";
return finish;
however this returns 1,65,7k instead of 1,657,108k.. anyone know why?

var formattedNumber = Math.round(yourNumber / 1000).toLocaleString() + "k";
Turn the above into a function or not as appropriate. I'm not aware of a single function to do this, or of a way to cater for non-English versions of "k" (assuming there are some), but at least toLocaleString() should take care of the comma versus fullstop for thousands issue.
UPDATE: I posted the above without testing it; when I tried it out I found toLocaleString() formatted 1234 as 1,234.00. I had thought of fixing it by using a regex replace to remove trailing zeros except of course I can't be sure what character toLocaleString() is going to use for the decimal point, so that won't work. I guess you could write some code that uses toLocaleString() on a "control" number (e.g., 1.1) to see at runtime what character it uses for the decimal.
UPDATE 2 for your updated question, inserting the commas manually, I did it like this:
var unformattedNumber = 123456;
var a = unformattedNumber.toString().split("");
for (var i=a.length-3; i >0; i-=3)
a.splice(i,0,",");
var formattedNumber = a.join("") + "k";

Related

Correctly format a whole number to a 2 decimal places output in JS but put 0 in front [duplicate]

I have a script which returns a price for a product. However, the price may or may not include trailing zeros, so sometimes I might have 258.22 and other times I might have 258.2. In the latter case, I need to add the trailing zero. How would I go about doing this?
You can use javascript's toFixed method (source), you don't need jQuery. Example:
var number = 258.2;
var rounded = number.toFixed(2); // rounded = 258.20
Edit: Electric Toolbox link has succumbed to linkrot and blocks the Wayback Machine so there is no working URL for the source.
Javascript has a function - toFixed - that should do what you want ... no JQuery needed.
var n = 258.2;
n.toFixed (2); // returns 258.20
I don't think jQuery itself has any string padding functions (which is what you're looking for). It's trivial to do, though:
function pad(value, width, padchar) {
while (value.length < width) {
value += padchar;
}
return value;
}
Edit The above is great for strings, but for your specific numeric situation, rosscj2533's answer is the better way to go.

Incrementing ID again from last row google apps script

last week I asked something here Increment ID from last row google apps script
Everything was working well but then again, when I used WP1-1000 as a starting row, the result is still appearing as WP1-0NaN
var riskid = mysheet.getRange(rlast,2).getValue();
if (riskid.length > 3){
// Extract number ex. 3
var riskidnb = parseInt(riskid.substring(1,riskid.length));
// Increase risk number +1
riskidnb++
// Convert to string "0004"
var s = "000" + riskidnb.toString();
// Write risk nb i.e. "R004"
mysheet.getRange(r,2).setValue("WP1-"+ s.substring(s.length-4))
}
I tried changing/increasing/decreasing the riskid.length, var s, and s.length-4 from the code but still no avail. The result still appears as "WP1-0NaN"
From my question, the string is already inverted into an integer, but it still appears as NaN when I changed it to WP1.
Also, it seems the code from my last question only workds if there is only 1 letter like in the solution.
I literally tried everything for 2 hours and going mad now.
Explanation / Issue:
That is because in your previous question, the id has the structure
of R-002 but now you are using 3 letters before the -:
WP1-1000. You can now use 4 instead of 1 and it will work:
parseInt(riskid.substring(4,riskid.length));
However, a more generic approach would be to substring after -, therefore you can use indexOf to find that position:
parseInt(riskid.substring(riskid.indexOf('-')+1,riskid.length));
You can apply the same logic for the last line. Instead of hardcopying WP1- you can just get the text before and including -:
riskid.substring(0,riskid.indexOf('-')+1);
Solution:
var riskid = mysheet.getRange(rlast,2).getValue();
if (riskid.length > 3){
// Extract number ex. 3
var riskidnb = parseInt(riskid.substring(riskid.indexOf('-')+1,riskid.length));
// Increase risk number +1
riskidnb++
// Convert to string "0004"
var s = "000" + riskidnb.toString();
// Write risk nb i.e. "R004"
var start = riskid.substring(0,riskid.indexOf('-')+1);
mysheet.getRange(r,2).setValue(start + s.substring(s.length-4))
}

jQuery: Content of html element is interpreted as a string, not an integer

When somebody is liking a comment on my website, a "1" is added at the right of the number where the amount of likes are shown, but when they click dislike, it does correct math.
For example:
14 + 1 = 141
14 - 1 = 13
jQuery
var elem = $('.like_button'), //Like button
num = $('.num_likes'), //Get the element: number of likes
oldnum = num.html(); //Number of likes
if(elem.html() == "Like") {
elem.html("Dislike");
num.html(oldnum+1); //Adds one like after liking it
} else {
elem.html("Like");
num.html(oldnum-1); //Deletes one like after disliking it
}
I really wonder why disliking works but liking not.
Why does javascript interpret the value of the num element as a string, even though it is a number? Any tips for me?
Because JavaScript interprets num.html() as text. The + sign for string in javascript means concatenation, but - doesn't mean that so in that case javascript realizes you want to do numeric calculation. That's why it works with -
You should cast oldnum to an integer with parseInt().
You need to cast oldnum to a number:
if(elem.html() == "Like") {
elem.html("Dislike");
num.html(Number(oldnum)+1); //Adds one like after liking it
} else {
elem.html("Like");
num.html(Number(oldnum)-1); //Deletes one like after disliking it
}
Alternatively, +oldnum does the same thing as Number(oldnum).
Javascript is interpreting the text on your page as a string. This is because that's what text on a page normally is. Take for example:
<span id="berliner">I am a jelly donut.</span>
<script LANGUAGE="Javascript">
document.getElementById("berliner").innerHTML;
// it only makes sense that this be a string, right?
</script>
Now, in JS, you use the + sign for two things: adding numbers, or putting one string after another.
var addingnumbers = 1+1;
// adding numbers, what you want
var a = "I am";
var b = " a jelly donut";
var addingstrings = a+b;
// adding strings, which you don't want.
As such, the html was interpreted as a string like it normally should be, but in this case shouldn't be. And adding the string to the other string just appended it to the end, rather than doing math. There is an easy solution: convert the innerHTML to a number by multiplying it by 1. Multiplying can't be done to a string, so JS will change it to number form, prepping it to be added to something else.
var oldnum = num.html()*1; // done! The multiplying has changed it to a number.
And if you ever do want to change it back to a string, you can do the reverse with the toString() function.
var aNumberToStartOutWith = 3;
var aStringToEndOffWith = aNumberToStartOutWith.toString();

Remove plus sign (+) in URL query string

I am trying get the string in the following URL to display on my webpage.
http://example.com?ks4day=Friday+September+13th
EDIT: The date in the URL will change from person to person as it's merged in by my CRM program.
I can get it to display on my webpage using the code below, the problem is the plus signs (+) come through as well.
eg. Friday+September+13th
What I need it to do is replace the plus signs (+) with spaces so it looks like this:
eg. Friday September 13th
I'm new to this so I'm having some trouble working it out.
Any help would be appreciated.
This is the code i'm using in a .js file
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
This is the code i'm using on my webpage to make it display
<script type="text/javascript">document.write(qs("ks4day"));</script>
Although Bibhu's answer will work for this one case, you'll need to add decodeURIComponent if you have encoded characters in your URI string. You also want to make sure you do the replace before the decode in case you have a legitimate + in your URI string (as %2B).
I believe this is the best general way to do it:
var x = qs("ks4day"); // 'Friday+September+13th'
x = x.replace(/\+/g, '%20'); // 'Friday%20September%2013th'
x = decodeURIComponent(x); // 'Friday September 13th'
Here's an example of when it might be useful:
var x = '1+%2B+1+%3D+2';
x = x.replace(/\+/g, '%20'); // '1%20%2B%201%20%3D%202'
x = decodeURIComponent(x); // '1 + 1 = 2'
You can use replace() for this purpose
var dateString = 'Friday+September+13th';
var s = dateString .replace(/\+/g, ' ');
Parsing strings using regex is often prone to so many errors. Thankfully all modern browsers provide URLSearchParams to handle params from url strings in a proper way:
var params = new URLSearchParams(window.location.search);
var value = params.get('ks4day');
// "Friday September 13th"
Ps: There is also a good polyfill for old browsers.
Have you tried https://www.npmjs.com/package/querystring ?
import { parse } from 'querystring';
parse('ks4day=Friday+September+13th')
returns
{ 'ks4day': 'Friday September 13th' }
Assuming you are using something like Webpack that knows how to process import statements
If that's what you are doing, the plus sign will not be the only one that is going to give you a hard time. The apostrophe ('), equals (=), plus (+) and basically anything not in the permitted URL characters (see Percent-encoding # Wikipedia) is going to get escaped.
You are most likely looking for the decodeURIComponent function.

JQuery adding number value

can someone help me debug this please???
i'm really don't know whats wrong with my code...
i'm trying to add number value to another number value.... but it does not work as i expected...instead it just add the number as a string.
Here is my demo:
(already solved)
and here is the js code:
$(document).ready(function(){
$("#map").click(function(e){
var x = parseInt((e.pageX - this.offsetLeft)) - parseInt("140");
var y = parseInt((e.pageY - this.offsetTop)) - parseInt("140");
var coor = $("#map").css("background-position").split(" ");
var cx = parseInt(coor[0].replace("px",""));
var cy = parseInt(coor[1].replace("px",""));
$("#map").stop().animate({"backgroundPosition": x+cx+" "+y+cy},"slow");
alert("X:"+x+", CX: "+cx+"\n Y:"+y+", CY:"+cy+"\n Background-pos:"+$("#map").css("background-position"));
});
});
please tell me what's wrong with it...
Put parentheses () around your arithmetic operations.
$("#map").stop().animate({"backgroundPosition": (x+cx)+" "+(y+cy)},"slow");
Otherwise, adding the whitespace string will force the JS to concatenate your numbers as a string.
Fiddle example
In your animate-Statement towards the end you set background position to:
x+cx+" "+y+cy
This is interpreted as a string, because the four +-operations are interpreted equally. You do, really, concatinate a string (" "). Thus, the entire result of this expression becomes a string and the addition is no longer an addition but a concat.
However, if you capsulate the math into parenthesis, then you should be fine. Your second-last line becomes:
$("#map").stop().animate({"backgroundPosition": (x+cx)+" "+(y+cy)},"slow");
(note the extra brackets around x+cx)
Isn't it ?
var x = parseInt((e.pageX - $(this).offset().left)) - parseInt("140");
var y = parseInt((e.pageY - $(this).offset().top)) - parseInt("140");
The following works for me:
$("#map").click(function(e){
alert(e.pageX);
alert(this.offsetLeft);
alert(parseInt(e.pageX)-parseInt(this.offsetLeft));

Categories