I'm trying to to increment the last decimal of a number from 1.234 to 1.235
var numb = 1.234;
numb.replace(/\d$/, numb + 1);
or let just say that the problem is like following
var oNumber = 1.34567
var oDecimalCount = 5
increaseNumber(oNumber, oDecimalCount){
oNumber += //increase the 5th(oDecimalCount) decimal place
}
You could do this :
count the numbers after the decimal point
use this number to remove the decimal point * 10^n
add 1
use the number to place the decimals back in place / 10^n
//I found this function here : https://www.tutorialspoint.com/decimal-count-of-a-number-in-javascript
const decimalCount = num => {
// Convert to String
const numStr = String(num);
// String Contains Decimal
if (numStr.includes('.')) {
return numStr.split('.')[1].length;
};
// String Does Not Contain Decimal
return 0;
}
let numb = 1.234;
let count = decimalCount(numb);
console.log(((numb * 10 ** count) + 1) / 10 ** count);
Im not sure I understand the question completely, but can't you just do it like this
let numb = 1.234;
numb += 0.001;
Related
I've been trying to figure out how to add period as a string in a certain place, here's the code
function fixBalance(amount){
if(amount <= 99999999){
var amt = "0." + amount.toString().padStart(8, "0");
return Number(amt);
} else {
return false;
}
}
console.log(fixBalance(1));
console.log(fixBalance(1000));
console.log(fixBalance(10000000));
console.log(fixBalance(1000000000));
Basically, there are 8 spaces to the right of the 0
After it passes 8 numbers, I want numbers to keep going past the period
For example:
1 = 0.00000001
1000 = 0.00001000 or 0.00001
10000000 = 0.10000000 or 0.1
100001000 = 0.100001000
1000000001 = 10.00000001
1010000000 = 10.10000000
10100000000 = 101.00000000
If I were to put in 1000000000, it should be 10.00000000 or 10 as a numerical number
Trying to figure out how to do that with the else statement
Thank you!
How about determining the integer and decimal parts separately before composing them?
function fixBalance(amount){
const divisor = 100_000_000;
const integer = Math.floor(amount / divisor);
const decimal = amount % divisor;
return integer.toString() + "." + decimal.toString().padStart(8, "0");
}
console.log(fixBalance(1));
console.log(fixBalance(1000));
console.log(fixBalance(10000000));
console.log(fixBalance(1000000000));
I have this decimal number: 1.12346
I now want to keep only 4 decimals but I want to round down so it will return: 1.1234. Now it returns: 1.1235 which is wrong.
Effectively. I want the last 2 numbers: "46" do round down to "4" and not up to "5"
How is this possible to do?
var nums = 1.12346;
nums = MathRound(nums, 4);
console.log(nums);
function MathRound(num, nrdecimals) {
return num.toFixed(nrdecimals);
}
If you're doing this because you need to print/show a value, then we don't need to stay in number land: turn it into a string, and chop it up:
let nums = 1.12346;
// take advantage of the fact that
// bit operations cause 32 bit integer conversion
let intPart = (nums|0);
// then get a number that is _always_ 0.something:
let fraction = nums - intPart ;
// and just cut that off at the known distance.
let chopped = `${fraction}`.substring(2,6);
// then put the integer part back in front.
let finalString = `${intpart}.${chopped}`;
Of course, if you're not doing this for presentation, the question "why do you think you need to do this" (because it invalidates subsequent maths involving this number) should probably be answered first, because helping you do the wrong thing is not actually helping, but making things worse.
I think this will do the trick.
Essentially correcting the round up.
var nums = 1.12346;
nums = MathRound(nums, 4);
console.log(nums);
function MathRound(num, nrdecimals) {
let n = num.toFixed(nrdecimals);
return (n > num) ? n-(1/(Math.pow(10,nrdecimals))) : n;
}
This is the same question as How to round down number 2 decimal places?. You simply need to make the adjustments for additional decimal places.
Math.floor(1.12346 * 10000) / 10000
console.log(Math.floor(1.12346 * 10000) / 10000);
If you want this as a reusable function, you could do:
function MathRound (number, digits) {
var adjust = Math.pow(10, digits); // or 10 ** digits if you don't need to target IE
return Math.floor(number * adjust) / adjust;
}
console.log(MathRound(1.12346, 4));
var nums = 1.12346;
var dec = 10E3;
var intnums = Math.floor(nums * dec);
var trim = intnums / dec;
console.log(trim);
var num = 1.2323232;
converted_num = num.toFixed(2); //upto 2 precision points
o/p : "1.23"
To get the float num :
converted_num = parseFloat(num.toFixed(2));
o/p : 1.23
In JavaScript when value is 4.3, i want it to round off to 4 and if value is 4.5 or above it rounds off to 5. I want all this without using Math.round().
You could also do this:
round=num=>(num-~~num>=0.5?1:0)+~~num;
Explanation:
~~num
is a double bitwise OR, actually it removes everything behind the point so 1.5 => 1
num-~~num
gets the distance to the next lower integer, so e.g. 5.4 => 0.4, 5.6 => 0.6
Some testcases:
http://jsbin.com/gulegoruxi/edit?console
Alternatively, you could transform the number into a string, split it, and round it with the help of a ternary operator.
Example:
// Decimal number
let number = 4.3;
// Convert it into a string
let string = number.toString();
// Split the dot
let array = string.split('.');
// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber = +array[0]; // 4
let secondNumber = +array[1]; // 3
// Now you can round it checking the second number
let rounded = secondNumber < 5 ? firstNumber : firstNumber + 1; // 4
In one line of code
let rounded = +number.toString().split('.')[1] < 5 ? +number.toString().split('.')[0] : +number.toString().split('.')[0] + 1;
You can do this
function RoundNum(number){
var c = number % 1;
return number-c+(c/1+1.5>>1)*1
}
console.log(RoundNum(2.456));
console.log(RoundNum(102.6));
console.log(RoundNum(203.515));
I am trying to split binary number in half and then just add 4 zeroes.
For example for 10111101 I want to end up with only the first half of the number and make the rest of the number zeroes. What I want to end up would be 10110000.
Can you help me with this?
Use substring to split and then looping to pad
var str = '10111101';
var output = str.substring( 0, str.length/2 );
for ( var counter = 0; counter < str.length/2; counter++ )
{
output += "0";
}
alert(output)
try this (one-liner)
var binary_str = '10111101';
var padded_binary = binary_str.slice(0, binary_str.length/2) + new Array(binary_str.length/2+1).join('0');
console.log([binary_str,padded_binary]);
sample output
['10111101','10110000']
I guess you are using JavaScript...
"10111101".substr(0, 4) + "0000";
It's a bit unclear if you are trying to operate on numbers or strings. The answers already given do a good job of showing how to operate on a strings. If you want to operate with numbers only, you can do something like:
// count the number of leading 0s in a 32-bit word
function nlz32 (word) {
var count;
for (count = 0; count < 32; count ++) {
if (word & (1 << (31 - count))) {
break;
}
}
return count;
}
function zeroBottomHalf (num) {
var digits = 32 - nlz32(num); // count # of digits in num
var half = Math.floor(digits / 2);// how many to set to 0
var lowerMask = (1 << half) - 1; //mask for lower bits: 0b00001111
var upperMask = ~lowerMask //mask for upper bits: 0b11110000
return num & upperMask;
}
var before = 0b10111101;
var after = zeroBottomHalf(before);
console.log('before = ', before.toString(2)); // outputs: 10111101
console.log('after = ', after.toString(2)); // outputs: 10110000
In practice, it is probably simplest to covert your number to a string with num.toString(2), then operate on it like a string as in one of the other answers. At the end you can convert back to a number with parseInt(str, 2)
If you have a real number, not string, then just use binary arithmetic. Assuming your number is always 8 binary digits long - your question is kinda vague on that - it'd be simply:
console.log((0b10111101 & 0b11110000).toString(2))
// 10110000
The following function works perfect, but when the amount over 1 million, the function don't work exactly.
Example:
AMOUNTPAID = 35555
The output is: 35.555,00 - work fine
But when the amount paid is for example: 1223578 (over 1 Million),
is the output the following output value: 1.223.235,00 (but it must be: 1.223.578,00) - there is a deviation of 343
Any ideas?
I call the function via HTML as follows:
<td class="tr1 td2"><p class="p2 ft4"><script type="text/javascript">document.write(ConvertBetrag('{{NETAMOUNT}}'))</script> €</P></TD>
#
Here ist the Javascript:
function Convertamount( amount ){
var number = amount;
number = Math.round(number * Math.pow(12, 2)) / Math.pow(12, 2);
number = number.toFixed(2);
number = number.toString();
var negative = false;
if (number.indexOf("-") == 0)
{
negative = true ;
number = number.replace("-","");
}
var str = number.toString();
str = str.replace(".", ",");
// number before decimal point
var intbeforedecimaln = str.length - (str.length - str.indexOf(","));
// number of delimiters
var intKTrenner = Math.floor((intbeforedecimaln - 1) / 3);
// Leading digits before the first dot
var intZiffern = (intbeforedecimaln % 3 == 0) ? 3 : (intbeforedecimaln % 3);
// Provided digits before the first thousand separator with point
strNew = str.substring(0, intZiffern);
// Auxiliary string without the previously treated digits
strHelp = str.substr(intZiffern, (str.length - intZiffern));
// Through thousands of remaining ...
for(var i=0; i<intKTrenner; i++)
{
// attach 3 digits of the nearest thousand group point to String
strNew += "." + strHelp.substring(0, 3);
// Post new auxiliary string without the 3 digits being treated
strHelp = strHelp.substr(intZiffern, (strHelp.length - intZiffern));
}
// attach a decimal
var szdecimal = str.substring(intbeforedecimaln, str.length);
if (szdecimal.length < 3 )
{
strNew += str.substring(intbeforedecimaln, str.length) + '0';
}
else
{
strNew += str.substring(intbeforedecimaln, str.length);
}
var number = strNew;
if (negative)
{
number = "- " + number ;
}
return number;
}
JavaScript's Math functions have a toLocaleString method. Why don't you just use this?
var n = (1223578.00).toLocaleString();
-> "1,223,578.00"
The locale you wish to use can be passed in as a parameter, for instance:
var n = (1223578.00).toLocaleString('de-DE');
-> "1.223.578,00"