I have several cases that I need to cover while dividing the numbers.
RULES:
- Division must always return 2 decimal places
- There must be no rounding.
This is the logic that I use:
function divideAndReturn (totalPrice, runningTime) {
let result;
let totalPriceFloat = parseFloat(totalPrice).toFixed(2);
let runningTimeNumber = parseInt(runningTime, 10); // Always a round number
result = totalPriceFloat / runningTimeNumber; // I do not need rounding. Need exact decimals
return result.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]; // Preserve only two decimals, avoiding rounding up.
}
It works as expected for the following case:
let totalPrice = '1000.00';
let runningTime = '6';
// result is 166.66
It also works for this case:
let totalPrice = '100.00';
let runningTime = '12';
// Returns 8.33
But for this case, it does not work as expected:
let totalPrice = '1000.00';
let runningTime = '5';
// Returns 200. Expected is 200.00
It seems when I divide numbers that are round, the division itself removes the .00 decimal places
If there is a fix for my logic, please shed some light. Or if there is a better way to cover it, I am also happy.
PS. Numbers are coming from the database, and are always initially strings.
The recommended strategy would be to first multiply the number with 100 (if your require 3 digit after decimal then 1000 and so on). Convert the result to integer and then divide by 100.
function divideAndReturn (totalPrice, runningTime) {
let result;
let totalPriceFloat = parseFloat(totalPrice); // no need to format anything right now
let runningTimeNumber = parseInt(runningTime, 10); // Always a round number
result = parseInt((totalPriceFloat * 100) / runningTimeNumber); // I do not need rounding. Need exact decimals
result /= 100
return result.toFixed(2) // returns a string with 2 digits after comma
}
console.log(divideAndReturn('1000.00', 6))
console.log(divideAndReturn('100.00', 12))
console.log(divideAndReturn('1000.00', 5))
You can try adding toFixed(2) in result line:
result = (totalPriceFloat / runningTimeNumber).toFixed(2);
Use toFixed on the result to convert number to string in required format. Converting an integer number to string will never render and digits after decimal place.
function divideAndReturn (totalPrice, runningTime) {
let totalPriceFloat = parseFloat(totalPrice);
let runningTimeNumber = parseInt(runningTime, 10);
let result = totalPriceFloat / runningTimeNumber;
// without rounding result
let ret = result.toFixed(3)
return ret.substr(0, ret.length-1);
}
console.log(divideAndReturn('1000.00', '6'))
console.log(divideAndReturn('100.00', '12'))
console.log(divideAndReturn('1000.00', '5'))
To remove any "rounding" use toFixed(3) and discard last digit.
If I understand correctly, your goal is to return a well-formatted string as the output of the division, regardless the result is a round number or not.
Why don't you parse the 2 inputs as numbers, make the division, and then format the output to fit with waht you need ?
function divideAndReturn (totalPrice, runningTime) {
let result;
let totalPriceFloat = parseFloat(totalPrice); // no need to format anything right now
let runningTimeNumber = parseInt(runningTime, 10); // Always a round number
result = totalPriceFloat / runningTimeNumber; // I do not need rounding. Need exact decimals
return result.toFixed(2) // returns a string with 2 digits after comma
}
Related
I'm trying to solve the following Leetcode problem:
You are given a large integer represented as an integer array digits,
where each digits[i] is the ith digit of the integer. The digits are
ordered from most significant to least significant in left-to-right
order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of
digits.
Example 1:
Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array
represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be [1,2,4].
Here's my code :
var plusOne = function(digits) {
let newDigit = digits.join('')
if (newDigit.length > 15) {
let digitLength = newDigit.length
let secondHalf = newDigit.slice(digitLength - 15, digitLength)
secondHalf = parseInt(secondHalf) + 1
secondHalf = Array.from(String(secondHalf), Number)
digits.splice(digitLength - 15, 15)
return digits.concat(secondHalf)
}
let Digit = parseInt(newDigit) + 1
const answer = Array.from(String(Digit), Number)
return answer
};
Works for many data sets. Get's the following error on the following set. Why :(
When you do parseInt(secondHalf), you're effectively dropping any leading zeros in that string, and as a result those zeros don't get included in the final array. The input digits are guaranteed not to have any leading zeros, but that doesn't mean that there won't be any leading zeros if you slice the string in the middle.
Also, even fixing that, what about input arrays that are longer than 30 characters?
Consider using a BigInt instead, it'll be a lot easier.
const plusOne = function(digits) {
const bigInt = BigInt(digits.join('')) + 1n;
return [...String(bigInt)].map(Number);
}
console.log(plusOne(
'590840235570031372488506112'.split('').map(Number)
));
I`m looking for a way to delete the last Digits from an Input with comma if the Value is more then 4.
Example:
Value : 13,314556 should be -> 13,3145.
Is there a way to just remove everything then the last 4 digits of this number with something like this?
let value = 13,314556
let result= value.split(',')[1].trim();
if(result.length > 4){
...
}
toFixed()
You can call toFixed() to format the number to a number of decimal places.
See MDN Documentation for toFixed()
Modified from the example given in the above documentation:
function myFormat(x) {
return Number.parseFloat(x).toFixed(4);
}
// expected output: "13.3146" because of rounding
console.log(myFormat(13.314556));
// expected output: "0.0040"
console.log(myFormat(0.004));
// expected output: "123000.0000"
console.log(myFormat('1.23e+5'));
If you don't want rounding, simply be more precise and clip the end of the resulting string.
function myFormat(x) {
return Number.parseFloat(x).toFixed(6).replace(/\d\d$/, '');
}
// expected output: "13.3145", will not do rounding
console.log(myFormat(13.314556));
If you are working with currency or do similar important calculations, consider working with a library like decimal.js.
alternative is to multiply by 10000, floor it, then divide by 10000.
let value = 13.314556;
value=Math.floor(value*10000)/10000;
console.log(value)
or if you want to control the number of digits programmatically you could use something like this:
let value = 13.314556;
value=Math.floor(value*Math.pow(10, 4))/Math.pow(10, 4);
console.log(value)
Maybe you are looking for slice function.
let value = "13,314556"
let result= value.split(',')[1].trim();
if(result.length > 4){
console.log(result.split('').slice(0,4).join(''))
}
I would do it with the slice and
join methods
Slice for slicing the string with the length you want
Join to re-create the number as you wish
Edit
I added check if comma is in the number and also a parameter with the desired length
function splitNumber(num, nbAfterComa) {
const number = num.toString()
if(!number.includes('.')){
return number
}
const splitedValue = number.split('.')
splitedValue[1] = splitedValue[1].trim().slice(0, nbAfterComa);
return nbAfterComa > 0 ? splitedValue.join(',') : splitedValue[0]
}
console.log(splitNumber(13.314556, 4))
console.log(splitNumber(13.3, 4))
console.log(splitNumber(13.314556, 1))
console.log(splitNumber(13.314556, 0))
console.log(splitNumber(13, 8))
I am trying to format numbers in JS to last two decimal.
For example 10100 becomes 101.00 - 606000 becomes 6,060.00 - 7600 becomes 76.00 and so on.
I have tried num.toFixed(2) but that was not of help. I also tried Number(10100).toLocaleString("es-ES", {minimumFractionDigits: 0}) but I end up with 10.100 so it seems off by one decimal.
So
num.toFixed(2)
What its doing its formatting,
Which would be 10.123 -> 10.12
what you should do is divide number by 100.
var number = 10100
number = number / 100
would be what you need.
I will approach this problem by using the help of strings.
Strings can be easily manipulated based on our requirements and then can be converted back to numbers. So, the solution goes like this
Convert the number to string
Manipulate the string to add a decimal before last two character
Convert the string back to number
const formatNumberToLastTwoDecimal = (number) => {
// Convert the number to String
const inputNumAsStr = number.toString();
// Manipulate the string and add decimal before two char
const updatedStr = `${inputNumAsStr.slice(0, -2)}.${inputNumAsStr.slice(-2)}`;
// Return by converting the string to number again
// Fix by 2 to stop parseFloat() from stripping zeroes to right of decimal
return new Number(parseFloat(updatedStr)).toFixed(2);
}
console.log(formatNumberToLastTwoDecimal(606000));
The most simplified way:
output = (number/100).toFixed(2)
And the complex way:
var c = 7383884
a = c.toString()
var output = parseFloat([a.slice(0, -2), ".",a.slice(-2)].join(''))
document.write(output)
I have one php function and having
phpans = round(53.955,2)
and javascript function
var num = 53.955;
var jsans = num.toFixed(2);
console.log(jsans);
both jsans and phpans is giving different $phpans = 53.96 ans jsans = 53.95 . I can not understand why this is happening ..
Thanks is Advance
Because computers can't represent floating numbers properly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiply by 100, round, then divide by 100 so the computer is only dealing with whole numbers.
var start = 53.955,
res1,
res2;
res1 = start.toFixed(2);
res2 = (start * 100).toFixed(0) / 100;
console.log(res1, res2);
//Outputs
"53.95"
53.96
JAvascript toFixed:
The toFixed() method converts a number into a string, keeping a specified number of decimals.
php round:
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Conclusion tofixed not working like php round. precision Specifies the number of decimal digits to round to.
Javascript function :
function round_up (val, precision) {
power = Math.pow (10, precision);
poweredVal = Math.ceil (val * power);
result = poweredVal / power;
return result;
}
From my understanding the binary number system uses as set of two numbers, 0's and 1's to perform calculations.
Why does:
console.log(parseInt("11", 2)); return 3 and not 00001011?
http://www.binaryhexconverter.com/decimal-to-binary-converter
Use toString() instead of parseInt:
11..toString(2)
var str = "11";
var bin = (+str).toString(2);
console.log(bin)
According JavaScript's Documentation:
The following examples all return NaN:
parseInt("546", 2); // Digits are not valid for binary representations
parseInt(number, base) returns decimal value of a number presented by number parameter in base base.
And 11 is binary equivalent of 3 in decimal number system.
var a = {};
window.addEventListener('input', function(e){
a[e.target.name] = e.target.value;
console.clear();
console.log( parseInt(a.number, a.base) );
}, false);
<input name='number' placeholder='number' value='1010'>
<input name='base' placeholder='base' size=3 value='2'>
As stated in the documentation for parseInt: The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
So, it is doing exactly what it should do: converting a binary value of 11 to an integer value of 3.
If you are trying to convert an integer value of 11 to a binary value than you need to use the Number.toString method:
console.log(11..toString(2)); // 1011
.toString(2) works when applied to a Number type.
255.toString(2) // syntax error
"255".toString(2); // 255
var n=255;
n.toString(2); // 11111111
// or in short
Number(255).toString(2) // 11111111
// or use two dots so that the compiler does
// mistake with the decimal place as in 250.x
255..toString(2) // 11111111
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
So you are telling the system you want to convert 11 as binary to an decimal.
Specifically to the website you are referring, if you look closer it is actually using JS to issue a HTTP GET to convert it on web server side. Something like following:
http://www.binaryhexconverter.com/hesapla.php?fonksiyon=dec2bin°er=11&pad=false
The shortes method I've found for converting a decimal string into a binary is:
const input = "54654";
const output = (input*1).toString(2);
print(output);
I think you should understand the math behind decimal to binary conversion. Here is the simple implementation in javascript.
main();
function main() {
let input = 12;
let result = decimalToBinary(input);
console.log(result);
}
function decimalToBinary(input) {
let base = 2;
let inputNumber = input;
let quotient = 0;
let remainderArray = [];
let resultArray = [];
if (inputNumber) {
while (inputNumber) {
quotient = parseInt(inputNumber / base);
remainderArray.push(inputNumber % base);
inputNumber = quotient;
}
for (let i = remainderArray.length - 1; i >= 0; i--) {
resultArray.push(remainderArray[i]);
}
return parseInt(resultArray.join(''));
} else {
return `${input} is not a valid input`;
}
}
This is an old question, however I have another solution that might contribute a little bit. I usually use this function to convert a decimal number into a binary:
function dec2bin(dec) {
return (dec >>> 0).toString(2);
}
The dec >>> 0 converts the number into a byte and then toString(radix) function is called to return a binary string. It is simple and clean.
Note: a radix is used for representing a numeric value. Must be an integer between 2 and 36. For example:
2 - The number will show as a binary value
8 - The number will show as an octal value
16 - The number will show as an hexadecimal value
function num(n){
return Number(n.toString(2));
}
console.log(num(5));
This worked for me: parseInt(Number, original_base).toString(final_base)
Eg: parseInt(32, 10).toString(2) for decimal to binary conversion.
Source: https://www.w3resource.com/javascript-exercises/javascript-math-exercise-3.php
Here is a concise recursive version of a manual decimal to binary algorithm:
Divide decimal number in half and aggregate remainder per operation until value==0 and print concatenated binary string
Example using 25: 25/2 = 12(r1)/2 = 6(r0)/2 = 3(r0)/2 = 1(r1)/2 = 0(r1) => 10011 => reverse => 11001
function convertDecToBin(input){
return Array.from(recursiveImpl(input)).reverse().join(""); //convert string to array to use prototype reverse method as bits read right to left
function recursiveImpl(quotient){
const nextQuotient = Math.floor(quotient / 2); //divide subsequent quotient by 2 and take lower limit integer (if fractional)
const remainder = ""+quotient % 2; //use modulus for remainder and convert to string
return nextQuotient===0?remainder:remainder + recursiveImpl(nextQuotient); //if next quotient is evaluated to 0 then return the base case remainder else the remainder concatenated to value of next recursive call
}
}
To get better understanding, I think you should try to do the math of that conversion by yourself.
(1) 11 / 2 = 5
(1) 5 / 2 = 2
(0) 2 / 2 = 1
(1) 1 / 2 = 0
I made a function based on that logic
function decimalToBinary(inputNum) {
let binary = [];
while (inputNum > 0) {
if (inputNum % 2 === 1) {
binary.splice(0,0,1);
inputNum = (inputNum - 1) / 2;
} else {
binary.splice(0,0,0);
inputNum /= 2;
}
}
binary = binary.join('');
console.log(binary);
}
This is what I did to get the solution:
function addBinary(a,b) {
// function that converts decimal to binary
function dec2bin(dec) {
return (dec >>> 0).toString(2);
}
var sum = a+b; // add the two numbers together
return sum.toString(2); //converts sum to binary
}
addBinary(2, 3);
I first converted the decimal number to binary like it said, and I got the function from w3schools under the JavaScript Bitwise lesson. Then to make it easier on myself, I created the variable "sum" which does the addition and finally, I made the addBinary function return the sum as a binary code, then called it. It passed in CodeWars. I hope this makes sense and it helps you.
Just use Number(x).toString(base). Where base needs to be equals 2.
var num1=13;
Number(num1).toString(2)
result: "1101"
Number(11).toString(2)
result: "1011"
It seems like the conversion with the string radix (dec >>> 0).toString(2) is returning the binary number formatted in the wrong direction. I have validated this solution in Chrome. In case anyone wants to manually calculate binary for validation, from left to right you add the numbers together that correspond to a 1 position in your binary number mapping to [1][2][4][8][16][32][64][128] ....
For example:
10 in binary is 0101 OR 0 + 2 + 0 + 8.
13 in binary is 1011 OR 1 + 0 + 4 + 8.
255 in binary is 11111111 OR 1 + 2 + 4 + 8 + 16 + 32 + 64 + 128
function dec2bin(dec){
return (dec >>> 0).toString(2).split('').reverse().join('');
}
This will give the decimal to binary:
let num = "1234"
console.log(num.toString(2));
This will give binary to decimal:
let num = "10011010010";
console.log(parseInt(num, 2));