Replace the decimal dot with a comma on an axis in D3? - javascript

This is about the ticks on axes in D3: Is there a way to replace the decimal dot with a comma in numbers? I want the numbers to be displayed like this (which is normal in Germany, such a big number is just for demonstration)
1.000.000,1 // This is one million and a tenth
and not like this:
1,000,000.1
I've read the documentation about the topic, but it seems like there is no possibility!? That's my relevant code so far:
localeFormatter = d3.locale({
"decimal": ".",
"thousands": ",",
"grouping": [3],
"currency": ["", "€"],
"dateTime": "%a, %e %b %Y, %X",
"date": "%d.%m.%Y",
"time": "%H:%M:%S",
"periods": ["", ""],
"days": ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
"shortDays": ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
"months": ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
"shortMonths": ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"]
});
numberFormat = localeFormatter.numberFormat("04.,"); // The setting is applied, but has not the desired effect...
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(numberFormat);

Using the following settings for d3.locale:
var localeFormatter = d3.locale({
"decimal": ",",
"thousands": ".",
...
});
Note that I have changed the . in , and vice versa. And with:
var numberFormat = localeFormatter.numberFormat(",.2f");
I print the number using a thousands separator , (it uses a . as defined in the locale) and two digits after the comma .2f:
console.log(numberFormat(1000000.1)); // "1.000.000,10"

Related

how could i change the string data format ..?

The data format, which I get from back-end is
{
"2020-08-22": 1425,
"2020-08-23": 1475,
"2020-08-24": 1475,
"flightnumber": "EK-853",
"source": "emirates",
"stops": "stops-0"
}
Is that possible to change the key data as following
{
"Aug 22": 1425,
"Aug 23": 1475,
"Aug 24": 1475,
"flightnumber": "EK-853",
"source": "emirates",
"stops": "stops-0"
}
Please tell me some solution for this.
Below snippet could help you. It has several things to notice:
iterate through object's keys
object's dynamic key
detect invalid date
const data = {
"2020-08-22": 1425,
"2020-08-23": 1475,
"2020-08-24": 1475,
flightnumber: "EK-853",
source: "emirates",
stops: "stops-0",
}
const monthNames = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
const res = {}
Object.keys(data).forEach((k) => {
const date = new Date(k)
if (!isNaN(date.getTime())) {
res[`${monthNames[date.getMonth()]} ${date.getDate()}`] = data[k]
} else {
res[k] = data[k]
}
})
console.log(res)

What is the proper way to match key and value to some variable using Javascript array?

I'm trying to create a function in javascript in order to get a value that match an external variable.
I created an array of key/value. Then I made a function that will check if a value match to a variable. Then i will return the key of this value.
function findNumberFromMonth($data)
{
var obj = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
}
for(var element in obj)
{
if($data == element.value )
{
$number = element.key
}
return $number;
}
}
I expected the output of "01" if i initialize $data as "Jan".
But i only got an undefined object.
How may i process ?
Thank you for your replies.
This can be done with find and Object.entries:
function findNumberFromMonth(data) {
const months = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
};
return Object.entries(months).find(([key, val]) => data === val)[0];
}
console.log(findNumberFromMonth('Oct'));
you can do this.
var obj = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
}
var key = Object.keys(obj)[Object.values(obj).indexOf("Jun")]
console.log(key)
If what you want to do is map month names to month numbers, your object is backwards:
function findNumberFromMonth($data)
{
var months = {
"Jan": "01",
"Feb": "02",
"Mar": "03",
// ...
};
return months[$data];
}
if you need both keys and values simultaneously, use object.entries and iterate over it.
const data = "Feb";
const obj = {
"01": "Jan",
"02": "Feb",
"03": "Mar",
"04": "Apr",
"05": "May",
"06": "Jun",
"07": "Jul",
"08": "Aug",
}
for (let [key, value] of Object.entries(obj)) {
if(data === value )
{
console.log(key);
}
}
When you use for(let x in obj) x is the key of the object.for...in.
function findNumberFromMonth($data)
{
var obj = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
}
for(var key in obj)
{
if($data == obj[key]) return key;
}
}
console.log(findNumberFromMonth('Jan'));
You assign $number variable in if statement. But return it in out of if statement. You must move return line to if statement and if not returned anything, you can return false value.
function findNumberFromMonth($data) {
var obj = {
01: "Jan",
02: "Feb",
03: "Mar",
04: "Apr",
05: "May",
06: "Jun",
07: "Jul",
08: "Aug",
09: "Sep",
10: "Oct",
11: "Nov",
12: "Dec"
}
for (var key in obj) {
if ($data === obj[key])
return key;
}
return false;
}
console.log(findNumberFromMonth('Mar'));

How to set global values for daterangepicker?

Github: Bootstrap Daterangepicker, plugin source: daterangepicker.js
I want to set global values for the locale option. I don't want to set it for each element every time I use it.
Here is an example code how to setup daterangepicker for a specific element.
$('#demo').daterangepicker({
"locale": {
"format": "MM/DD/YYYY",
"separator": " - ",
"applyLabel": "Apply",
"cancelLabel": "Cancel",
"fromLabel": "From",
"toLabel": "To",
"customRangeLabel": "Custom",
"weekLabel": "W",
"daysOfWeek": [
"Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa"
],
"monthNames": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"firstDay": 1
},
"startDate": "12/01/2016",
"endDate": "12/07/2016"
}, function(start, end, label) {
console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
});
Is it even possible? Or do I have to rewrite the plugin?
What's the best approach if this is not possible without some custom modification?
you can store the dateRangePickerSettings as a global variable
var dateRangePickerSettings = {
locale: {...},
};
and reference it to all ur plugin instances
$('#demo1').daterangepicker({
"locale": dateRangePickerSettings.locale,
"startDate": "06/01/2016",
"endDate": "06/07/2016"
});
$('#demo2').daterangepicker({
"locale": dateRangePickerSettings.locale,
"startDate": "12/01/2016",
"endDate": "12/07/2016"
});
Dan Grossman added support in 2.1.26
Added support for $.fn.daterangepicker.defaultOptions to set default options for all pickers on page.
Lets try to explain it here for newcomers.
$.fn.daterangepicker.defaultOptions = {
locale: {
"format": "DD/MM/YYYY",
"separator": " - ",
"applyLabel": "Aplicar",
"cancelLabel": "Cancelar",
"fromLabel": "Desde",
"toLabel": "Hasta",
"customRangeLabel": "Personalizado",
"weekLabel": "W",
"firstDay": 0,
"daysOfWeek": ["Lu","Ma","Mi","Ju","Vi","Sa","Do"],
"monthNames": [
"Enero",
"Febrero",
"Marzo",
"Abril",
"Mayo",
"Junio",
"Julio",
"Agosto",
"Septiembre",
"Octubre",
"Noviembre",
"Diciembre",
]
}
}
$('#period').daterangepicker();
Thanks to #kurdemol94

Bootstrap datepicker error when using other language: Uncaught TypeError: Cannot read property 'length' of undefined

I'm using the datepicker from Bootstrap (http://bootstrap-datepicker.readthedocs.org/en/latest/i18n.html). When using datepicker without the "language" property, it works, but when I try to specify a language ("sv"), it fails with the message (i.e when trying to select a date in the widget):
Uncaught TypeError: Cannot read property 'length' of undefined
These are the versions I'm using:
jQuery v1.8.3
jQuery UI 1.8.22
Boostrap 2.3.1
From looking at the debugger it seems that this is the code that crashes (Datetimepicker.prototype, the row with "p: "):
formatDate: function (date, format, language, type) {
if (date == null) {
return '';
}
var val;
if (type == 'standard') {
val = {
// year
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear(),
// month
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
// day
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
p: (dates[language].meridiem.length == 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : ''),
// hour
h: date.getUTCHours(),
// minute
i: date.getUTCMinutes(),
// second
s: date.getUTCSeconds()
};
This is the working code (a widget in english):
var dates = $('#date-picker input[name=from_date], .facet-container input[name=to_date]').datetimepicker({
format: 'yyyy-mm-dd',
autoclose:'true',
todayBtn:'true',
pickerPosition:'bottom-left',
minView:'month'
}).on('changeDate', function(ev){
});
This crashes:
$.fn.datetimepicker.dates['sv'] = {
days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"],
daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"],
daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö"],
months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Idag",
clear: "Rensa"
};
var dates = $('#date-picker input[name=from_date], .facet-container input[name=to_date]').datetimepicker({
format: 'yyyy-mm-dd',
autoclose:'true',
weekStart: 1,
language:'sv',
todayBtn:'true',
pickerPosition:'bottom-left',
minView:'month'
}).on('changeDate', function(ev){
});
What could be the problem??
This fixed it, i.e had to add a "meridiem" property:
$.fn.datetimepicker.dates['sv'] = {
days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"],
daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"],
daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö"],
months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
meridiem: '',
today: "Idag",
clear: "Rensa"
};

Change language for bootstrap DateTimePicker

I use bootstrap-datetimepicker.js Copyright 2012 by Stefan Petre
http://www.malot.fr/bootstrap-datetimepicker/index.php
I import the js and another language, for example Russian:
<script type="text/javascript"
src="/Resources/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js"></script>
<script type="text/javascript"
src="/Resources/plugins/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.ru.js" charset="UTF-8"></script>
in document.ready
$(document).ready(function () {
// debugger;
$(".form_datetime").datetimepicker({
isRTL: false,
format: 'dd.mm.yyyy hh:ii',
autoclose:true
});
});
but it is not translated
I tried to insert on init
**language: "RU"**
**language: "ru"**
**language: "ru-RU"**
but nothing changes,
Do you have any proposal?
i think you have to set it in the options:
$(".form_datetime").datetimepicker({
isRTL: false,
format: 'dd.mm.yyyy hh:ii',
autoclose:true,
language: 'ru'
});
if its not working, be sure that:
$.fn.datetimepicker.dates['en'] = {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today"
};
is defined for 'ru'
If you use moment.js the you need to load moment-with-locales.min.js not moment.min.js. Otherwise, your locale: 'ru' will not work.
you need to add the javascript language file,after the moment library, example:
<script type="text/javascript" src="js/moment/moment.js"></script>
<script type="text/javascript" src="js/moment/es.js"></script>
now you can set a language.
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({locale:'es'});
});
</script>
Here are all language: https://github.com/moment/moment
The option is locale: 'ru'
But first, you have to call the script ../moment.js/version/locale/ru.js
Hope this helps.
Just include your desired locale after the plugin. You can find it in locales folder on github https://github.com/uxsolutions/bootstrap-datepicker/tree/master/dist/locales
<script src="bootstrap-datepicker.XX.js" charset="UTF-8"></script>
and then add option
$('.datepicker').datepicker({
language: 'XX'
});
Where XX is your desired locale like ru
1.you will use different locale array element in datepicker.js from following link
https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales
2.add array in datepicker.js like this:
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today"
},
CN:{
days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
today: "今天",
suffix: [],
meridiem: ["上午", "下午"]
}
};
1.First add this js file to your HTML.
<script th:src="#{${webLinkFactory.jsLibRootPath()}+'/bootstrap-datepicker.nl.min.js'}" charset="UTF-8"type="text/javascript"></script>
obviously after moment.min.js.
content of bootstrap-datepicker.nl.min.js will be
;(function($){
$.fn.datepicker.dates['nl'] = {
days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
daysShort: ["Zon", "Man", "Din", "Woe", "Don", "Vri", "Zat", "Zon"],
daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Vandaag",
suffix: [],
meridiem: []
};
$.fn.datetimepicker.dates['nl'] = {
days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
daysShort: ["Zon", "Man", "Din", "Woe", "Don", "Vri", "Zat", "Zon"],
daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Vandaag",
suffix: [],
meridiem: []
};
}(jQuery));
2.set this line in the ready function of your js file.
$(document).ready(function () {
$.fn.datetimepicker.defaults.language = 'nl';
}
3.initialize your datetimepicker in this way
$(this).datetimepicker({
format: "yyyy-mm-dd hh:ii",
autoclose: true,
weekStart: 1,
locale: 'nl',
language: 'nl'
});
following this steps i was able to convert my english datepicker and datetimepicker to dutch successfully.
all you are right! other way to getting !
https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.ru.min.js
You can find out all languages on there https://cdnjs.com/libraries/bootstrap-datepicker
https://labs.maarch.org/maarch/maarchRM/commit/3299d1e7ed25018b48715e16a42d52c288b4da3e
For those who like me could not solve this problem with the solutions above, I sugest verifying if you initialize the $(element).datetimepicker(...) in different locations at the same time.
In my case, after a long time, I found a global.js interfering with another datetimepicker initialization.
If you need for some reason maintain work with different initializations, in different files, remember to remove the datetimepicker before each one with:
$(element).datetimepicker('remove')
Reference: https://www.malot.fr/bootstrap-datetimepicker/index.php#methods
Edit: This solution still needs to import the language files correctly, right after the bootstrap-datetimepicker.js.
I hope this helps!
for french speaker, this how you do it
;(function($){
$.fn.datepicker.dates['fr'] = {
days: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"],
daysShort: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."],
daysMin: ["d", "l", "ma", "me", "j", "v", "s"],
months: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
monthsShort: ["janv.", "févr.", "mars", "avril", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."],
today: "Aujourd'hui",
monthsTitle: "Mois",
clear: "Effacer",
weekStart: 1,
format: "dd/mm/yyyy"
};
}(jQuery));
$('.js-datepicker').datepicker({
format: 'dd/mm/yyyy',
startDate: new Date(),
language: 'fr',
});
thx to this source from : https://www.1formatik.com/1056/comment-mettre-bootstrap-datepicker-en-francais
This is for your reference only:
https://github.com/rajit/bootstrap3-datepicker/tree/master/locales/zh-CN
https://github.com/smalot/bootstrap-datetimepicker
https://bootstrap-datepicker.readthedocs.io/en/v1.4.1/i18n.html
The case is as follows:
<div class="input" id="event_period">
<input class="date" required="required" type="text">
</div>
$.fn.datepicker.dates['zh-CN'] = {
days:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
daysShort:["周日","周一","周二","周三","周四","周五","周六"],
daysMin:["日","一","二","三","四","五","六"],
months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
monthsShort:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],
today:"今日",
clear:"清除"
};
$('#event_period').datepicker({
inputs: $('input.date'),
todayBtn: "linked",
clearBtn: true,
format: "yyyy年mm月",
titleFormat: "yyyy年mm月",
language: 'zh-CN',
weekStart:1 // Available or not
});
Try this:
$( ".form_datetime" ).datepicker( $.datepicker.regional[ "zh-CN" ], { dateFormat: 'dd.mm.yyyy hh:ii' });

Categories

Resources