I need to format numbers to two decimal digits in javascript. In order to do this I am using toFixed method which is working properly.
But in cases, where numbers don't have any decimal digits, it should not show decimal point
e.g. 10.00 should be 10 only and not 10.00.
.toFixed() converts the result to String,
so you need to convert it back to Number:
parseFloat( num.toFixed(2) )
or by simply using the Unary +
+num.toFixed(2)
both will give the following:
// 15.00 ---> 15
// 15.20 ---> 15.2
If you only want to get rid of the .00 case, than you can go for String manipulation using .replace()
num.toFixed(2).replace('.00', '');
Note: the above will convert your Number to String.
As an alternative to make this change global(if you need, of course), try this:
var num1 = 10.1;
var num2 = 10;
var tofixed = Number.prototype.toFixed;
Number.prototype.toFixed = function(precision)
{
var num = this.valueOf();
if (num % 1 === 0)
{
num = Number(num + ".0");
}
return tofixed.call(num, precision);
}
console.log(num1.toFixed(2));
console.log(num2.toFixed(2));
Fiddle. This is a mix of this and this post.
Related
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 want to have 2 decimals in a number.
I tried using :
var number = (123).toFixed(2);
but it returns it in a string format. I want them to be numbers.
Also I tried using:
var number= parseFloat((123).toFixed(2));
but this removes the decimals if it is 0.
I want to show the numbers as decimals with fixed 2 decimals, also convert those numbers to toLocaleString("bn-IN-u-nu-latn")
For example:
number = 123456
output : 1,23,456.00
That's impossible. A number won't display trailing zeros past the decimal point. Only a string will.
For example, observe this output:
document.write(0.00); // output as a number, is 0
document.write("<br>");
document.write("0.00"); // output as a string, is 0.00
If you want a number to be rounded to two decimal places, but also have trailing zeros when needed, you must convert to a string before you output, which means (123).toFixed(2) is all you need.
Edit: To round the number, but also use a locale format. Use .toLocaleString() like such:
(0.00).toLocaleString("bn-IN-u-nu-latn", {
minimumFractionDigits:2,
maximumFractionDigits:2
});
Try :
var number = +parseFloat(Math.round(123 * 100) / 100).toFixed(2);
You can try this ..
Html
Value: <input type="text" id="myText" value="">
Javascript
<script>
num = 125;
num=num+1;
var R = num.toFixed(2); // returns 126.00
document.getElementById("myText").value = R;
</script>
Please see below screen......
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));
I am using this code:
$("#total_percentage").text(
(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10))
);
My problem is that #total_percentage sometimes gives a long result.
e.g: 2.33333333333
Is there a way to setting it so it rounds up / shows only max of 2 digits?
for example: 2 or 10
To round up use the Javascript Math library.
$("#total_percentage").text(
(Math.ceil(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10)))
);
You can use toFixed():
$("#total_percentage").text(
(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10)).toFixed(2)
);
References:
toFixed().
If you want to display two digits to the right of the decimal, Math.toFixed is the solution:
(2.33333333).toFixed(2) === "2.33"
Note that this results in a string, not a number. If you want to display 2 digits total, Math.toPrecision is what you want:
(2.33333333).toPrecision(2) === "2.3"
Again, this results in a string. To get back to a number (if desired), you can use parseFloat.
A final note that both these functions will also round your number. For example:
(1.23456).toPrecision(4) === "1.235"
If you want to truncate your number without rounding, you can write a function like this:
function truncate(num,precision) {
var muldiv = Math.pow(10,precision-1);
return Math.floor(num * muldiv) / muldiv;
}
truncate(1.23456,4) === 1.234
Here is a jsFiddle demonstrating each method:
---jsFiddle DEMO---
When I want to select the nth character, I use the charAt() method, but what's the equivalent I can use when dealing with integers instead of string values?
Use String():
var number = 132943154134;
// convert number to a string, then extract the first digit
var one = String(number).charAt(0);
// convert the first digit back to an integer
var one_as_number = Number(one);
It's a stupid solution but seems to work without converting to string.
var number = 123456789;
var pos = 4;
var digit = ~~(number/Math.pow(10,pos))- ~~(number/Math.pow(10,pos+1))*10;
You could convert the number to a string and do the same thing:
parseInt((number + '').charAt(0))
If you want an existing method, convert it to a string and use charAt.
If you want a method that avoids converting it to a string, you could play games with dividing it by 10 repeatedly to strip off enough digits from the right -- say for 123456789, if you want the 3rd-from-right digit (6), divide by 10 3 times yielding 123456, then take the result mod 10 yielding 6. If you want to start counting digits from the left, which you probably do, then you need to know how many digits (base 10) are in the entire number, which you could deduce from the log base 10 of the number... All this is unlikely to be any more efficient than just converting it to a string.
function digitAt(val, index) {
return Math.floor(
(
val / Math.pow(10, Math.floor(Math.log(Math.abs(val)) / Math.LN10)-index)
)
% 10
);
};
digitAt(123456789, 0) // => 1
digitAt(123456789, 3) // => 4
A bit messy.
Math.floor(Math.log(Math.abs(val)) / Math.LN10)
Calculates the number of digits (-1) in the number.
var num = 123456;
var secondChar = num.toString()[1]; //get the second character
var number = 123456789
function return_digit(n){
r = number.toString().split('')[n-1]*1;
return r;
}
return_digit(3); /* returns 3 */
return_digit(6); /* returns 6 */