d3.format thousand separator on variables? - javascript

Hello I'm yet again stuck on d3...
I'd like to know how to use a thousand seperator on a variable all the examples I've managed to find seem to be on static data.
This is what I've tried so far:
d3.csv("OrderValueToday.csv", function(obj) {
var text = 'Today = £';
var totalSales = text + d3.format(",") + obj[0].Today;
svgLabel = d3.select("#label").append("h2")
.text (totalSales);
});
However it just outputs a load a stuff on the webpage this is it:
Today = £function (n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a; if(0>p){var c=Zo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}20000
So all I want is to be able to make the totalSales value have thousand separators so like 20,000 everything else I've tried doesnt do anything. I've read this https://github.com/mbostock/d3/wiki/Formatting but didnt see what I could do for my scenario.
Any help would be greatly appreciated. Cheers

Specifying a d3.format returns a formatting function, which you must then call as a function, passing in the number to be formatted as an argument:
var myNumber = 22400;
d3.format(',')(myNumber); // returns '22,400'
Sometimes you will see a format function stored as a variable like this:
var commaFormat = d3.format(',');
commaFormat(1234567); // returns '1,234,567'
In your case, you could do the following:
var totalSales = text + d3.format(',')(obj[0].Today);

Related

How to get the first 3 digits from a cell

So I have got a column and i want to get the first 3 digits only from it and store them in a function called wnS using the split function or any other method that would work. I want to get the first three digits before "_"
I tried doing this but it didn't work, and I also kept getting "TypeError: wnC.split is not a function"
var ssh = ssPO.getSheetByName("PO for OR (East).csv")
wnC = ssh.getRange("N2:N");
var wnS = wnC.split("_");
I would really appreciate an answer
If you need more info please let me know
Thank you.
After you define range, you have to get the values.
function first_3_digs (){
var ssh = ssPO.getSheetByName("PO for OR (East).csv")
var wnC = ssh.getRange("N2:N");
var values = wnC.getValues();
const first_3_digs = values.filter(r => {
if(r.toString().includes('_')){return r;}
}).map(r=> r.toString().split('_')[0]);
console.log(first_3_digs)
}
const cell = "(303) 987-4567";
const first3 = cell.match(/\d{3}/)[0];
//result:303
String method match()
regular expression
BTW: you can test methods like this very easily in the console.log in the browsers developer tools.

Why method setValue doesn't output same as Browser.msgBox?

Since I could not make .toFixed(2) to work I designed my own piece of code to add desired decimal digits after the "." by simple joining two strings with + sign.
While Browser.msgBox outputs the 2 strings joined correctly as "1.00",
it seems like getRange.setValue outputs only the first of the 2 strings as "1" :(
function myFunction() {
var ss_calc = SpreadsheetApp.openById("1cFt0DbnpWGHquKk4ijxdKhwkaF8GhumWDWjTpHuSXbQ");
var sheet_calc = ss_calc.getSheetByName("Calcs");
var ss_source = SpreadsheetApp.openById("1gXeXmiw9EnzQXaiE7H8_zrilE2zyotlSuuIS8X9IxfQ");
var sheet_source = ss_source.getSheetByName("Farmah");
var decDig = ""; var strDec = ""; var impVal = "";
impVal = sheet_source.getRange(12,7).getValue().toString();
if (JSON.stringify(impVal).indexOf(".")>-1)
{ if (JSON.stringify(impVal).split(".")[1].length < 2 )
{
if (JSON.stringify(impVal).split(".")[1].length < 1)
{
decDig = "00";
}
else
{
decDig = "0";
}
}
}
else
{
decDig = ".00";
}
var strDec = impVal.toString() + decDig.toString();
Browser.msgBox(JSON.stringify(impVal).indexOf(".")+ "\\n" +
impVal.toString()+ "\\n" +
decDig+ "\\n" +
strDec);
sheet_calc.getRange(1,1).setValue(strDec);
}
From sheet_calc.getRange(1,1).setValue(strDec); I am expecting to get output "1.00" but I get only "1" :(
What am I missing?
Here are the links to google spreadsheets ( anyone with the link can edit :)
(above code has to be triggered manually by script editor in the first spreadsheet here under):
https://docs.google.com/spreadsheets/d/1cFt0DbnpWGHquKk4ijxdKhwkaF8GhumWDWjTpHuSXbQ/edit?usp=sharing
https://docs.google.com/spreadsheets/d/1gXeXmiw9EnzQXaiE7H8_zrilE2zyotlSuuIS8X9IxfQ/edit?usp=sharing
You want to put the value of 1.00 to a cell "A1".
If my understanding is correct, how about this modification? I think that the reason of your issue is that the value by putting by setValue() is converted to the number. By this, 1 is shown. In order to put the value as 1.00, I think that there are 3 patterns. Please select one of them for your situation.
Pattern 1:
In this pattern, from your question, the value is put as a string using setNumberFormat("#").
From:
sheet_calc.getRange(1,1).setValue(strDec);
To:
sheet_calc.getRange(1,1).setNumberFormat("#").setValue(strDec);
Pattern 2:
In this pattern, from your question, the format of cell is set using setNumberFormat("0.00").
From:
sheet_calc.getRange(1,1).setValue(strDec);
To:
sheet_calc.getRange(1,1).setNumberFormat("0.00").setValue(strDec);
Pattern 3:
In this pattern, from the script of your shared Spreadsheet, When decDig is ".00", the format is set.
From:
sheet_calc.getRange(x+6,c).setValue(strDec);
To:
var range = sheet_calc.getRange(x+6,c);
if (decDig) {
range.setNumberFormat("0.00").setValue(strDec); // or setNumberFormat("#")
} else {
range.setValue(strDec);
}
Reference:
setNumberFormat(numberFormat)
If I misunderstood your question and this was not the result you want, I apologize.
From sheet_calc.getRange(1,1).setValue(strDec); I am expecting to get output "1.00" but I get only "1" :(
Google Sheets, as well as other spreadsheet apps, have an automatic data type assignation, so things that look as numbers are converted to Google Sheets number data type, etc.
You could prepend an ' to force that a value be treated as text or you could set the number format in such way that numbers are displayed with two decimals. The cell formatting could be applied in advance, i.e., by using the Google Sheets UI commands or you could use Apps Script to set the format for you.

Subtract 1 from variable jQuery

Having some trouble getting this right. I'm very new to jQuery, so trying to get better and learn.
Currently I am getting 2 different values from a html table using the following code
var sellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var buyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
These both output a value such as $13,000,000
I am then wanting to subtract 1 from these values (making it $12,999,999) before pasting them to an input as such
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
However, I am having some trouble with how to subtract $1 from these.
I tried using sellPrice--; but without success.
I've also tried adding - 1; at the end of each variable, but did not succeed either.
I tried to test something like this, but did not work either.
var minusOne = -1;
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = (getCurrentSellPrice - minusOne);
var buyPrice = (getCurrentBuyPrice - minusOne);
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);`
Trying my best to familiarize myself with jQuery :)
Any help is much appreciated!
Solved using this
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = Number(getCurrentSellPrice.replace(/[^0-9\.]+/g,"")) - 1;
var buyPrice = Number(getCurrentBuyPrice.replace(/[^0-9\.]+/g,"")) + 1;
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
Since your numbers contain currency symbol and are strings, you need to convert them to proper numbers before subtracting them. See the answer below.
How to convert a currency string to a double with jQuery or Javascript?

Finding the difference between two fields using JavaScript in iText

I would like to find difference between two fields using JavaScript in iText.
I am able to find the sum of them using below code:
PdfStamper stamperResult = new PdfStamper(readersectionResult, new FileOutputStream(RESULT_NEW));
stamperResult .addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"total2\")')");
Is there any way to find the difference using 'AFSimple_Calculate' similar to what I did in the above code snippet?
Thanks for editing! I tried your suggestion but it does not seem to work for some reason.
stamperResult.addJavaScript(" var total1 = this.getField(\"value1\"); var total2 = this.getField (\"value2\"); var subtr = this.getField(\"total\"); subtr.value = total1.value - total2.value;");
I separated newlines by spaces and added right escape characters.
I was also thinking of using a different logic for subtraction using AF methods : like this
stamperResult.addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"-total2\")')");
In the above code I was trying to add -(negative value) to total 2 so that it will be subtracted from total1 though the AF method is still 'SUM'.
But that does not work.
The below simple code seem to work :
stamperResult.addJavaScript("var nameField = this.getField('total');" +
"nameField.setAction('Calculate'," +
"'subtract()');" +
"" +"function subtract(){this.getField('total').value
= (this.getField('total_1').value -this.getField('total_2').value); }");
I updated your question because it contained many spelling errors. I didn't edit the code snippet because I don't know what the original code snippet is like. In any case: I think something went wrong during the copy/paste process, as I don't think your code snippet compiles in its current state.
In any case: as far as I know the AF-methods (the AF stands for Adobe Forms) may not be present in every viewer, and as far as I know Adobe didn't implement a way to subtract values from each other in the AFSimple_Calculate method.
For these two reasons, you may prefer regular JavaScript instead of using a pre-canned function that may or may not be pre-canned.
This regular JavaScript may look like this:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var subtr = this.getField("difference");
subtr.value = total1.value - total2.value;
I'm not sure if that answers your question. Maybe you just want:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var namefield = total1.value - total2.value;
You can put these lines inside a String using the right escape characters and replacing the newlines by spaces or newline characters.
Of course, you need to trigger this code somewhere. Below you'll find an example that puts the negative value of the content of a value1 field into a value2 field.
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("js.pdf"));
document.open();
writer.addJavaScript("function makeNegative() { this.getField('value2').value = -(this.getField('value1').value); } ");
Rectangle rect1 = new Rectangle(40, 740, 200, 756);
TextField value = new TextField(writer, rect1, "value1");
value.setBorderColor(GrayColor.GRAYBLACK);
value.setBorderWidth(0.5f);
PdfFormField field = value.getTextField();
field.setAdditionalActions(PdfName.BL, PdfAction.javaScript("makeNegative();", writer));
writer.addAnnotation(field);
Rectangle rect2 = new Rectangle(40, 710, 200, 726);
TextField neg = new TextField(writer, rect2, "value2");
neg.setBorderColor(GrayColor.GRAYBLACK);
neg.setBorderWidth(0.5f);
writer.addAnnotation(neg.getTextField());
document.close();
}
Note that I used a Blur action. This means the method will be triggered as soon as you select another field after filling out the value1 field.

ExtJS 4.1.1: Evaluating a field in a grid

I'm struggling with a ExtJS 4.1.1 grid that has editable cells (CellEditing plugin).
A person should be able to type a mathematic formula into the cell and it should generate the result into the field's value. For example: If a user types (320*10)/4 the return should be 800. Or similar if the user types (320m*10cm)/4 the function should strip the non-mathematical characters from the formula and then calculate it.
I was looking to replace (or match) with a RegExp, but I cannot seem to get it to work. It keeps returning NaN and when I do console.log(e.value); it returns only the originalValue and not the value that I need.
I don't have much code to attach:
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
console.log(str);
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
var numCalc = Number(eval(strCalc));
console.log(numCalc);
return numCalc;
},
Which returns: str=321 strCalc=null numCalc=0 when I type 321*2.
Any help appreciated,
GR.
Update:
Based on input by Paul Schroeder, I created this:
onGridValidateEdit : function(editor,e,opts) {
var str = e.record.get(e.field).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
console.log(typeof numCalc);
console.log(numCalc);
return numCalc;
},
Which calculates the number, but I am unable to print it back to the grid itself. It shows up as "NaN" even though in console it shows typeof=number and value=800.
Final code:
Here's the final code that worked:
onGridValidateEdit : function(editor,e,opts) {
var fldName = e.field;
var str = e.record.get(fldName).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
e.record.set(fldName,numCalc);
},
Lets break this code down.
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
What listener is this code being used in? This is very important for us to know, here's how I set up my listeners in the plugin:
listeners: {
edit: function(editor, e){
var record = e.record;
var str = record.get("your data_index of the value");
}
}
Setting it up this way works for me, So lets move on to:
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
at which point strCalc=null, this is also correct. str.match returns null because your regex does not match anything in the string. What I think you want to do instead is this:
var strCalc = str.replace(/[^0-9+*-]/g, "");
console.log(strCalc);
This changes it to replace all characters in the string that aren't your equation operators and numbers. After that I think it should work for whole numbers. I think that you may actually want decimal numbers too, but I can't think of the regex for that off the top of my head (the . needs to be escaped somehow), but it should be simple enough to find in a google search.

Categories