Skip to content

Instantly share code, notes, and snippets.

@liabru
liabru / json-limit-precision.js
Last active Oct 4, 2021
Limit precision of floating point numbers in a JSON string in JavaScript
View json-limit-precision.js
var testObject = {
pi: Math.PI,
e: Math.E,
one: 1,
x: 1.5,
str: "1.2345"
};
var places = 2,
json = JSON.stringify(testObject, function(key, value) {
@liabru
liabru / save-file-local.js
Created Apr 24, 2014
Save a text file locally with a filename, by triggering a download in JavaScript
View save-file-local.js
/*
* Save a text file locally with a filename by triggering a download
*/
var text = "hello world",
blob = new Blob([text], { type: 'text/plain' }),
anchor = document.createElement('a');
anchor.download = "hello.txt";
anchor.href = (window.webkitURL || window.URL).createObjectURL(blob);
@liabru
liabru / read-local-file.js
Created Apr 24, 2014
Trigger a file open dialog and read local file in JavaScript
View read-local-file.js
/*
* Trigger a file open dialog and read local file, then read and log the file contents
*/
var element = document.createElement('div');
element.innerHTML = '<input type="file">';
var fileInput = element.firstChild;
fileInput.addEventListener('change', function() {
var file = fileInput.files[0];