Avoid Number() for scientific notation [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to do the below
Number("0.00000000000122") results in 1.22e-12
But what I need to just that number to get converted from String to Number.
console.log(Number("0.00000000000122"))

You can do it like this:
console.log(Number("0.00000000000122").toFixed(20).replace(/\.?0+$/,""));
Explanation:
toFixed() will keep the number, and replace() will remove trailing zeroes
Edit:
It seems that you want the result of Number("0.00000000000122") to BOTH be a number and also keep it string as "0.00000000000122", not its scientific display.
In that case, you can save it as a number-type variable in ts file, then display it as a string in HTML

If you want to work with precise numbers you have to work with integers.
A Number is not an integer type, it's a float so numbers are represented in memory as a float. The toString method of the number just prints out the value in memory. The integer bit and the dot location.
const scale = 18n;
const digits = 10n ** scale;
const POUND = (number) => BigInt(number) * digits;
const toPound = (number, fraction = false) => {
if (!fraction) {
return String(number / digits);
}
const str = String(number);
if (scale < 1n) {
return str;
}
return `${str.substring(0, Number(BigInt(str.length) - scale))}.${str.substr(-Number(scale))}`;
};
const a = POUND(11000);
const b = POUND(20000);
console.log('scale', String(scale));
console.log('a', toPound(a));
console.log('b', toPound(b));
console.log('mul', toPound((a * b) / digits));
console.log('add', toPound(a + b));
console.log('div', toPound(b / (a / digits), true));
console.log('sub', toPound(b - a));

Related

Create Function to get Next Number (including decimals) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I've created a function that returns the next number taking into account decimals, but am having an issue when the input number has a zero (0) proceeding the decimal.
const getNextValue = (input) => {
const newNumber = input
.toString()
.replace(/\d+$/, (number) =>
parseInt(number) +1)
return parseFloat(newNumber)
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.3 as it ignores the zeros
You could skip the zeros:
const getNextValue = (input) => {
const newNumber = input
.toString()
.replace(/^\d+$|[1-9]+$/, (number) =>
parseInt(number) + 1);
return parseFloat(newNumber)
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.003
console.log(getNextValue(30)) // returns 31
A completely different approach that should solve all the mentioned issues. I've added the character '1' in front of the decimal places to avoid the problem with leading zeros and to store the carry. At the end I add the carry and remove this character.
const getNextValue = (input) => {
const str = input.toString();
if (!str.includes('.')) return input + 1;
const numbers = str.split('.');
const dec = (+('1' + numbers[1]) + 1).toString();
return parseFloat(`${+numbers[0] + +dec[0] - 1}.${dec.substring(1)}`);
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.003
console.log(getNextValue(3.9)) // returns 4
console.log(getNextValue(3.09)) // returns 3.1
console.log(getNextValue(30)) // returns 31

how to add 1 in last item of array in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am solving one problem .but getting correct output for small array but my solution fail when array size is large
solution
/**
* #param {number[]} digits
* #return {number[]}
*/
var plusOne = function(digits) {
let str = parseInt(digits.join(''))+1+''
return str.split('')
};
Question
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
above cases are passed
failed cases
Input
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
let str = parseInt(digits.join(''))+1+''
With too many array elements, you are simply creating a number that is outside of the integer range here.
An implicit conversion to a float has to happen, and with that you get the inherent loss of precision - which then leads to several zeros in those places at the end, when you reverse the process.
Access the last array element specifically, and add 1 to the value. But if that last element had the value 9 already, you will of course have to repeat that same process for the previous one … basic application of “carry the one”.
var input = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9];
var output = [];
// loop over input array in reverse order
for(var i=input.length-1, toadd = 1; i>-1; --i) {
// add value `toadd` to current digit
var incremented = input[i] + toadd;
if(incremented < 10) {
output.unshift(incremented); // add to front of output array
toadd = 0; // reset toadd for all following digits, if we had no overflow
}
else {
output.unshift(0); // overflow occurred, so we add 0 to front of array instead
}
}
console.log(output)
This does take an “overflow” for 9 digits at the end into account; it does not handle the case when all digits are 9 though, if you need to handle that edge case as well, please implement that yourself.
This one recursively checks the last digits:
const test1 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const test2 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9]
const plusOne = function(digits) {
if(digits[digits.length - 1] === 9){
digits = [...plusOne(digits.slice(0, -1)), 0]
}else{
digits[digits.length - 1]++
}
return digits;
};
console.log(plusOne(test1));
console.log(plusOne(test2));
You could do something like this :
var arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3,9,9]
function plusOne(index){
if( index < 0 ) return ; // Base case
if(arr[index] === 9){
arr[index] = 0;
plusOne(index-1); // For carry ahead
}else{
arr[index] += 1
}
}
plusOne(arr.length-1) // start with last digit

miliseconds replace from 6 to 3 decimals with javascript jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to replace 02:04.887004 to 02:04.887 with jquery or js.
Other times I have microseconds just with four decimals (02:04.8348) and I would have 02:04.834
I would use regexp to find $:[d][d].$ and then return it but with the three decimals
If the length of the string is reliable, you can just trim the unwanted characters from the string, e.g.
let time = '02:04.887004';
// If format is reliable, get first 9 characters
console.log(time.substr(0,9));
// If length might vary and number of decimals is at least 3
// Trim from end
console.log(time.slice(0, -(time.length - time.indexOf('.') - 4)))
// Trim from start
console.log(time.substr(0, time.length - time.indexOf('.') + 2));
If the format is more unreliable, you have more work to do.
You can use a regular expression or a split function or a substring on the string to format your timestring. Here is an example of the three:
const time = '02:04.887004';
const regex = /[\d]{2}:[\d]{2}\.[\d]{3}/
const formatTime = time => {
const match = time.match(regex);
return match ? match[0] : match;
}
const formatTime2 = time => {
const m = time.split(':').shift();
const s = time.split(':').pop().split('.').shift();
const ms = time.split('.').pop().substr(0,3);
return m + ':' + s + '.' + ms;
}
const formatTime3 = time => {
return time.substr(0,9);
}
console.log(formatTime(time));
console.log(formatTime2(time));
console.log(formatTime3(time));

Truncate zeros from string in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I see questions asked on truncating the leading zeros, but nothing found to solve my issue. I have a array of strings representing days returning from an api call.
Ex:
arr= ["061-094", "0561-0960", "000-005", "180+"];
arr.map(function(d){
<div>{d} days</div> // this returns 061-094 days
});
1) How can I remove the leading zeros so that it displays like:
61-94 days
561-960 days
0-5 days
2) How can display:
more than 180 days
for "180+" value?
Thanks
You can use map to generate a new array by testing each value, and if it matches the nn-nn pattern, split the string into numbers, convert to number (removes leading zeros but keeps "0" as a single value), then put them back as strings.
If the string matches the nn+ pattern, process it accordingly.
E.g.
var arr = ["061-094", "0561-0960", "000-005", "180+"];
var result = arr.map(function(v) {
// deal with nn-nn
if (/\d+-\d+/.test(v)) {
return v.split('-').map(s => +s).join('-');
}
// Deal with nn+
if (/\d+\+/.test(v)) {
return v.replace(/(\d+).*/, 'more than $1 days');
}
});
console.log(result);
If you want to wrap in HTML, then do that too.
Assuming there's no other patterns in your data than 000-000 or 180+:
arr = ["061-094", "0561-0960", "000-005", "180+", "90+"];
var result = arr.map(function(d){
if (d.substr(-1) == "+") {
return "<div>More than " + d.slice(0,-1) + " days</div>";
}
var parts = d.split("-");
var truncatedParts = [];
parts.map(function(part) {
truncatedParts.push(parseInt(part, 10));
});
return "<div>" + truncatedParts.join("-") + " days</div>" ;
});
console.log(result);
Have you tired making a String to remove all leading zeros?
String strPattern = "^0+";
This should remove all leading zeros but not trailing zeros.

Algorithm to convert any string to a 1-3 digit number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to make an algorithm, for a NodeJS app, that converta any given string to a 1 to 3 digit number (better if the number is between 1-500).
e.g
ExampleString -> 214
Can anyone help me find a good solution?
EDIT:
I want to get a crime coefficient number from a username (string).
Ok, you can use JS function to get charCode of letter
let str = "some string example";
let sum = 0;
for (let i=0; i<str.length; i++) {
sum += parseInt(str[i].charCodeAt(0), 10); // Sum all codes
}
// Now we have some value as Number in sum, lets convert it to 0..1 value to scale to needed value
let rangedSum = parseFloat('0.' + String(sum)); // Looks dirty but works
let resultValue = Math.round(rangedSum * 500) + 1; // Same alogorythm as using Math.random(Math.round() * (max-min)) + min;
I hope it helps.
So as you are using nodejs, you can use crypto library to get md5 hash of string and then get it as HEX.
const crypto = require('crypto');
let valueHex = crypto.createHash('md5').update('YOUR STRING HERE').digest('hex');
// then get it as decimal based value
let valueDec = parseInt(valueHex, 16);
// and apply the same algorythm as above to scale it between 1-500
function coeficient() {
return Math.floor(Math.random() * 500) + 1;
}
console.log(coeficient());
console.log(coeficient());
console.log(coeficient());

Categories