Multiply points of a string - javascript

Let's say that I have a list of points declared in this format: x1,y1 x2,y2
listOfPoints : string = "12.2, 13.0 198.2, 141";
What could I do to multiply by 1.5, for example, every number of this string ?
Do I need to iterate over the listOfPoints and extract a string every time that there is a ', ' or ' ', convert that string into a number, multiply it by 1.5 and reconvert it into a string to finally put it into a new string (newListOfPoints) ?
Or is there a different way to that more efficiently ?
Thank you.

Use a regular expression with a replacer function to match digits, possibly with decimals, and replace with those digits multiplied by the number you want:
const listOfPoints = "12.2, 13.0 198.2, 141";
const multiplied = listOfPoints.replace(
/\d+(?:\.\d+)?/g,
match => match * 1.5
);
console.log(multiplied);
Due to floating-point issues, some of the resulting numbers may have trailing digits. If you don't want that, you can round the multiplied number to a certain number of decimal places:
const listOfPoints = "12.2, 13.0 198.2, 141";
const multiplied = listOfPoints.replace(
/\d+(?:\.\d+)?/g,
match => Math.round(1000 * match * 1.5) / 1000
);
console.log(multiplied);

Related

Using JavaScript, how do I use the .toExponential() function, but only using two decimal places (9.99e9, instead of 9.9999e9)

If I have a variable that is set to 2345, and I want to convert it to exponential, I simply do variableName.toExponential().replace(/e+?/, 'e'), which will give me 2.345e3. However, I want it to only return two decimal places there, because otherwise once I get to much larger numbers, like 183947122, I'll get a long decimal, 1.83947122e8. I want this to floor to 1.83e8, but I can't figure out where I would put variable.toFixed(2) in this code.
var a=1233434;
console.log(a.toExponential(2));
you can pass the parameter in .toExponential(2) function for rounding.it will give 2 number after decimal check this link https://www.geeksforgeeks.org/javascript-toexponential-function/
You could calculate the floored value and then apply toExponential.
const f = (x, p) => {
const l = 10 ** (Math.floor(Math.log10(Math.abs(x))) - p);
return (Math.floor(x / l) * l).toExponential(p);
}
console.log(f(183947122, 2));
console.log(f(-183947122, 2));
console.log(f(183947122, 4));
You can do it with a regular expression and replace (which you're already using to replace e+ with e):
const str = variableName.toExponential().replace(/^(\d*\.\d{0,2})\d*e\+(\d+)$/, "$1e$2");
That captures the whole number portion of the coefficient plus up to two fractional digits of it, ignores any others, and captures the full exponent; it replaces the match with $1$2 so you're left with just the up-to-two digits of the coefficient:
function test(variableName) {
const raw = variableName.toExponential();
const str = raw.replace(/^(\d*(?:\.\d{0,2})?)\d*e\+(\d+)$/, "$1e$2");
console.log(variableName, "=>", raw, "=>", str);
}
test(2345);
test(100);
test(1019);
test(183947122);

Generate big numbers with Math random in Javascript

I need to generate 26 digit numbers with Math.random, but when I use this:
Math.floor(Math.random() * 100000000000000000000000000) + 900000000000000000000000000
I gets 9.544695043285823e+26
Modern browsers support BigInt and bigint primitive type and we can combine it with a random generated array containing 8 bytes (the sizeof bigint is 8 bytes (64 bits)).
1. Generating Random BigInt Performance Wise
We can generate a random hex string of 16 characters length and apply it directly to BigInt:
const hexString = Array(16)
.fill()
.map(() => Math.round(Math.random() * 0xF).toString(16))
.join('');
const randomBigInt = BigInt(`0x${hexString}`);
// randomBigInt will contain a random Bigint
document.querySelector('#generate').addEventListener('click', () => {
const output = [];
let lines = 10;
do {
const hexString = Array(16)
.fill()
.map(() => Math.round(Math.random() * 0xF).toString(16))
.join('');
const number = BigInt(`0x${hexString}`);
output.push(`${
number.toString().padStart(24)
} : 0x${
hexString.padStart(16, '0')
}`);
} while (--lines > 0);
document.querySelector('#numbers').textContent = output.join('\n');
});
<button id="generate">Generate</button>
<pre id="numbers"><pre>
2. Generating Random BigInt from random bytes array
If we want to use Uint8Array or if we want more control over the bits manipulation, we can combine Array.prototype.fill with Array.prototype.map to generate an array containing 8 random byte number values (beware this is around 50% slower than the above method):
const randomBytes = Array(8)
.fill()
.map(() => Math.round(Math.random() * 0xFF));
// randomBytes will contain something similar to this:
// [129, 59, 98, 222, 20, 7, 196, 244]
Then we use Array.prototype.reduce to initialize a BigInt of zero value and left shift each randum byte value its position X 8 bits and applying bitwise or to the current value of each reduce iteration:
const randomBigInt = randomBytes
.reduce((n, c, i) => n | BigInt(c) << BigInt(i) * 8n, 0n);
// randomBigInt will contain a random Bigint
Working example generating 10 random BigInt values
document.querySelector('#generate').addEventListener('click', () => {
const output = [];
let lines = 10;
do {
const number = Array(8)
.fill()
.map(() => Math.round(Math.random() * 0xFF))
.reduce((n, c, i) => n | BigInt(c) << BigInt(i) * 8n, 0n);
output.push(`${
number.toString().padStart(24)
} : 0x${
number.toString(16).padStart(16, '0')
}`);
} while (--lines > 0);
document.querySelector('#numbers').textContent = output.join('\n');
});
<button id="generate">Generate</button>
<pre id="numbers"><pre>
Floating point numbers in JavaScript (and a lot of other languages) can contain only about 15.955 digits without losing precision. For bigger numbers you can look into JS libraries, or concatenate few numbers as strings. For example:
console.log( Math.random().toString().slice(2, 15) + Math.random().toString().slice(2, 15) )
Your question seems to be an XY problem where what you really want to do is generate a sequence of 26 random digits. You don't necessarily have to use Math.random. Whenever one mentions randomness it's important to specify how that randomness is distributed, otherwise you could end up with a paradox.
I'll assume you want each of the 26 digits to be independently randomly chosen uniformly from each of the 10 digits from 0 to 9, but I can also see a common interpretation being that the first digit must not be 0, and so that digit would be chosen uniformly from numbers 1 to 9.
Other answers may tempt you to choose a random bigint value using what amounts to random bits, but their digits will not be randomly distributed in the same way, since their maximum value is not a power of 10. For a simple example consider that a random 4 bit binary value in decimal will range from 00 to 15, and so the second digit will have a 12/16(=75%) chance of being 0 to 5, though it should be 60%.
As for an implementation, there's many ways to go about it. The simplest way would be to append to a string 26 times, but there are more potentially efficient ways that you could investigate for yourself if you find the performance isn't adequate. Math.random has a roughly uniform distribution from 0 to 1, but by being double precision it only has 15 or so significant decimal digits to offer us, so for each call to Math.random we should be able to retrieve up to 15 out of 26 decimal digits. Using this fact, I would suggest the following compromise on ease of readability and efficiency:
function generate26Digits() {
const first13 = Math.floor(Math.random() * Math.pow(10, 13)).toFixed(0).padStart(13, "0");
const next13 = Math.floor(Math.random() * Math.pow(10, 13)).toFixed(0).padStart(13, "0");
return first13 + next13;
}
console.log(generate26Digits())
This solution is not cryptographically secure however, and so I will direct readers to use Crypto.getRandomValues if you need more security for this for some reason.
If you then want to do math on this number as well without losing precision, you will have to use bigint types as others have suggested.
If I use a 6 decillion LG about 72.9 million out of 300 but when I switch to 10 centillion it comes like this 10 ^ 999 - 99999 + 26 just like how 9 - 9 - 9 - 9 - googolplex is equal to 0 googolplex

Javascript split integer and add decimal point

My integer value is 1210 and i want split this integer like 1 | 210 .Have to add decimal point on middle.
Eg:
var integer=1210;
Split this integer and add decimal value like this 1.210
Why don't you just divide the number by 1000
var x = 1210;
var y = 1210/1000; //1.210 number
var z = y+""; // 1.120 will be string here
console.log(y); // Will output 1.210
If you're always dealing with 4 digit numbers, dividing by 1000 will work (as mentioned in another answer) but you'll need to use toFixed to make sure javascript doesn't remove trailing zeros:
var x = 1210;
(x / 1000).toFixed(3) // => "1.210"
(x / 1000) + "" // => "1.21"
More generically you could use:
x=prompt('enter an integer');
xl=x.toString().length-1
alert((x/Math.pow(10,xl)).toFixed(xl));
(just make sure you enter an integer, preferably +ve, at the prompt)

Get the number and round to whole number

I'm getting the miles from Google Map API V3 and displaying it in a textbox based on the from and to addresses. I want to parse out the number and round it off to the nearest whole number.
Miles = "29.9 mi" // i want the result as 30
Miles = "9.3 mi" // 10
I tried Math.round but it's returning NAN.
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var miles = response.routes[0].legs[0].distance.text;
miles = Math.round(miles);
$('#TotalMiles').val(miles);
}
Did you look at the JavaScript API for round?
Syntax
Math.round(x)
Parameters
x A number.
Description
If the fractional portion of number is .5 or greater, the argument is
rounded to the next higher integer. If the fractional portion of
number is less than .5, the argument is rounded to the next lower
integer.
Because round is a static method of Math, you always use it as
Math.round(), rather than as a method of a Math object you created.
EDIT:
You need to convert the string into its parts to get the number
Miles = "29.9 mi"
var num = parseFloat(Miles);
Math.round(num);
and way to do it with a regular expression
Miles = "29 mi"
var rounded = Miles.replace(/(\d+(\.\d+)?)(\s?mi)/, function(match, number, x, units){ return Math.round(parseFloat(number)) + units });
console.log(rounded);
Try parseFloat + Math.ceil:
var number = "9.3 mi";
console.log(Math.ceil(parseFloat(number)));
you may need to split out the extra characters.
var str = "29.9 mi";
var number = str.split(" ");
var new_number = Math.round(parseFloat(number[0]));
This is a longwinded answer. In the end it would make more sense to tailor it to what you need exactly, but here I am just showing how to split on " " (space) and round the resulting string after parsing it as a float.
I would try KaeruCT's answer though. I don't think parseInt or parseFloat actually need the non numeric characters removed.
Try Math.round():
var number =29.9;
console.log(Math.round(number));

Truncate decimal number (as strings) to a fixed number of places

I want to truncate numbers (given as strings) to a fixed number of decimal places. The numbers can be negative (with a minus sign), positive (no sign). I'd prefer to round the numbers properly and keep trailing zeroes. I want the same number of decimal places, no matter how long the whole number is. The numbers will be stored back as strings.
For example:
140.234234234 -> 140.234
1.123123 -> 1.123
-12.789789 -> -12.790
First parse them as floats, then format with toFixed:
var nums = [
"140.234234234", // -> 140.234
"1.123123", // -> 1.123
"-12.789789" // -> -12.790
];
nums.forEach(function(n) {
console.log(parseFloat(n).toFixed(3));
});
http://codepen.io/anon/pen/IvxmA
Any number can be displayed as a fixed decimal place string by using .toFixed:
var num = 140.234234234;
var fixedDecimalPlace = num.toFixed(3); // is "140.234"
function truncate( numberString, trunk ) {
var onpoint = numberString.split('.',2);
var numberStringTruncated = numberString;
if (onpoint.length > 1) {
numberStringTruncated = onpoint[0] + '.' + onpoint[1].substring(0,trunk);
}
return numberStringTruncated;
}
This does not consider rounding or padding. As the other answer suggested, you should use parseFloat followed by toFixed

Categories

Resources