Delete digits after two decimal point not round number in javascript? - javascript

I have this :
i=4.568;
document.write(i.toFixed(2));
output :
4.57
But i don't want to round the last number to 7 , what can i do?

Use simple math instead;
document.write(Math.floor(i * 100) / 100);
(jsFiddle)
You can stick it in your own function for reuse;
function myToFixed(i, digits) {
var pow = Math.pow(10, digits);
return Math.floor(i * pow) / pow;
}
document.write(myToFixed(i, 2));
(jsFiddle)

Just cut the longer string:
i.toFixed(3).replace(/\.(\d\d)\d?$/, '.$1')

A slightly convoluted approach:
var i=4.568,
iToString = ​i + '';
i = parseFloat(iToString.match(/\d+\.\d{2}/));
console.log(i);
This effectively takes the variable i and converts it to a string, and then uses a regex to match the numbers before the decimal point and the two following that decimal point, using parseFloat() to then convert it back to a number.
References:
match()
parseFloat().
Regular Expressions.

Related

Javascript end to 2 decimals not working

i'm trying to set an output value from 2 fields to 2 decimals.
i've tried doing this with: .toFixed(2) but it didn't work for me. I tried doing this:
calculate = function () {
var total = document.getElementById('totaal').value;
var btw = document.getElementById('percentage').value;
document.getElementById('btw').value = parseInt(total.toFixed(2)) * parseInt(btw.toFixed(2)) / 100;
}
If the field ends on a number with 2 decimals (for example: 3,45) it is working correctly.But if it ends with a 0, it does not show the 0.
I think this shoudn't be this mutch of a deal but i'm just trying for half a day now...
Thanks in advance!
When you use parseInt() you then get the numbers after the decimal points removed, try doing this :
document.getElementById('btw').value = (parseFloat(total) * parseFloat(btw) / 100).toFixed(2);
parseFloat converts the string (and it's necessary because input values are string) in the input to a float, then divide by 100 and call .toFixed(2) on the result.
You could convert a string to number by using an unary plus +.
document.getElementById('btw').value = (+total * +btw / 100).toFixed(2);
If you use parseInt, you loose precision, which you may have.
You can use parseFloat to achieve this
var total =65633;
var btw = 12;
console.log(parseFloat((total* btw)/100).toFixed(2))
Your issues is that you're running toFixed() on strings, and toFixed() only works on numbers.
You could however, do this:
document.getElementById('btw').value =
(parseInt(total) * parseInt(btw) / 100).toFixed(2)
This takes the two numbers and does all the math. It then converts it to a string with two trailing decimals
See my fiddle here: https://jsfiddle.net/6vtrjmax/
Make sure you are calling toFixed on the entire operation i.e. document.getElementById("btw").value = (parseInt(total) * parseInt(btw) / 100).toFixed(2);
Try running the snippet below:
calculate = function() {
var total = document.getElementById("total").value;
var btw = document.getElementById("percentage").value;
if (total && btw) {
document.getElementById("btw").value =
(parseInt(total) * parseInt(btw) / 100).toFixed(2);
}
};
<input onchange="calculate()" placeholder='total' type="decimal" id="total">
<input onchange="calculate()" placeholder='percentage' type="decimal" id="percentage">
<input type="decimal" placeholder='result' id="btw">

Remove the last digits of a number (not string)

How can I remove the last digits of a number (not string) using JavaScript.
Example:
Input : 2121.1124
Output : 2121.112
I google it a lot. But everywhere I found remove string. How can I do it?
This is the code for remove last char of a string.
var str = "stackoverflow";
str = str.substring(0, str.length - 1);
console.log(str);
How can I do it for a digit(not string) ?
Use number.toFixed(amountOfDecimals); to round, where amountOfDecimals is 3.
Use Math.floor( number * Math.pow(10, amountOfDecimals) ) / Math.pow(10, amountOfDecimals); to avoid rounding. So, for 3 decimal places, that becomes Math.floor( 2121.1124 * 1000 ) / 1000;
Not sure which one you need.
Edited to reflect h2ooooooo's suggestion below.
You can display the decimal numbers using toFixed() like the following:
parseFloat(2121.1124).toFixed(3) this will return 2121.112
output= parseInt(input*1000)/1000
How does it work ?
the parseInt(input*1000) will remove all nums after the third after the decimal.

How to use division in JavaScript

I want to divide a number in JavaScript and it would return a decimal value.
For example: 737/1070 - I want JavaScript to return 0.68; however it keeps rounding it off and return it as 0.
How do I set it to return me either two decimals place or the full results?
Make one of those numbers a float.
737/parseFloat(1070)
or a bit faster:
737*1.0/1070
convert to 2 decimal places
Math.round(737 * 100.0 / 1070) / 100
(737/1070).toFixed(2); rounds the result to 2 decimals and returns it as a string. In this case the rounded result is 0.69 by the way, not 0.68. If you need a real float rounded to 2 decimals from your division, use parseFloat((737/1070).toFixed(2))
See also
Also you can to use [.toPrecision(n)], where n is (total) the number of digits. So (23.467543).toPrecision(4) => 23.47 or (1241876.2341).toPrecision(8) => 1241876.2.
See MDN
Try this
let ans = 737/1070;
console.log(ans.toFixed(2));
toFixed() function will do
to get it to 2 decimal places you can: alert( Math.round( 737 / 1070 * 100) / 100 )
with lodash:
const _ = require("lodash");
Use of _.divide() method
let gfg = _.divide(12, 5);
Printing the output
console.log(gfg)
2.4
credit

JavaScript displaying a float to 2 decimal places

I wanted to display a number to 2 decimal places.
I thought I could use toPrecision(2) in JavaScript .
However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.
See it on JSbin.
What is the best way to do this?
I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?
float_num.toFixed(2);
Note:toFixed() will round or pad with zeros if necessary to meet the specified length.
You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.
number.parseFloat(2) works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
with toFixed you can set length of decimal points like this:
let number = 6.1234
number.toFixed(2) // '6.12'
but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.
let number = 6
number.toFixed(2) // '6.00'
to avoid this you have to convert the result to a number. you can do this with these two methods:
let number1 = 6
let number2 = 6.1234
// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12
// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
Try toFixed instead of toPrecision.
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // return 1.01
round(1.004, 2); // return 1 instead of 1.00
The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/
I used this way if you need 2 digits and not string type.
const exFloat = 3.14159265359;
console.log(parseFloat(exFloat.toFixed(2)));
You could try mixing Number() and toFixed().
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
$('#message').text( myNumber * multiplier );
});
$('#actionButton2').on('click', function() {
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>
<div id="message"></div>
The toFixed() method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError, RangeError
Here is the full detail and compatibility in the browser.
let a = 0.0500
a.toFixed(2);
//output
0.05
There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.
Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');
Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:
Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
float_num = parseFloat(float_num.toFixed(2))
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}

How can I round a number in JavaScript? .toFixed() returns a string?

Am I missing something here?
var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string
Why does .toFixed() return a string?
I want to round the number to 2 decimal digits.
Number.prototype.toFixed is a function designed to format a number before printing it out. It's from the family of toString, toExponential and toPrecision.
To round a number, you would do this:
someNumber = 42.008;
someNumber = Math.round( someNumber * 1e2 ) / 1e2;
someNumber === 42.01;
// if you need 3 digits, replace 1e2 with 1e3 etc.
// or just copypaste this function to your code:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
.
Or if you want a “native-like” function, you can extend the prototype:
Number.prototype.toFixedNumber = function(digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(this*pow) / pow;
}
someNumber = 42.008;
someNumber = someNumber.toFixedNumber(2);
someNumber === 42.01;
//or even hexadecimal
someNumber = 0xAF309/256; //which is af3.09
someNumber = someNumber.toFixedNumber(1, 16);
someNumber.toString(16) === "af3.1";
However, bear in mind that polluting the prototype is considered bad when you're writing a module, as modules shouldn't have any side effects. So, for a module, use the first function.
I've solved this problem by changing this:
someNumber = someNumber.toFixed(2)
...to this:
someNumber = +someNumber.toFixed(2);
However this will convert the number to a string and parse it again, which will have a significant impact on performance. If you care about performance or type safety, check the the other answers as well.
It returns a string because 0.1, and powers thereof (which are used to display decimal fractions), are not representable (at least not with full accuracy) in binary floating-point systems.
For example, 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and 0.01 is really 0.01000000000000000020816681711721685132943093776702880859375. (Thanks to BigDecimal for proving my point. :-P)
Therefore (absent a decimal floating point or rational number type), outputting it as a string is the only way to get it trimmed to exactly the precision required for display.
Why not use parseFloat?
var someNumber = 123.456;
someNumber = parseFloat(someNumber.toFixed(2));
alert(typeof(someNumber));
//alerts number
I solved it with converting it back to number using JavaScript's Number() function
var x = 2.2873424;
x = Number(x.toFixed(2));
Of course it returns a string. If you wanted to round the numeric variable you'd use Math.round() instead. The point of toFixed is to format the number with a fixed number of decimal places for display to the user.
You can simply use a '+' to convert the result to a number.
var x = 22.032423;
x = +x.toFixed(2); // x = 22.03
May be too late to answer but you can multiple the output with 1 to convert to number again, here is an example.
const x1 = 1211.1212121;
const x2 = x1.toFixed(2)*1;
console.log(typeof(x2));
What would you expect it to return when it's supposed to format a number ? If you have a number you can't pretty much do anything with it because e.g.2 == 2.0 == 2.00 etc. so it has to be a string.
Because its primary use is displaying numbers? If you want to round numbers, use Math.round() with apropriate factors.
To supply an example of why it has to be a string:
If you format 1.toFixed(2) you would get '1.00'.
This is not the same as 1, as 1 does not have 2 decimals.
I know JavaScript isn't exactly a performance language, but chances are you'd get better performance for a rounding if you use something like:
roundedValue = Math.round(value * 100) * 0.01
You should use it like below.
var someNumber: number = 0.000000;
someNumber = Number(someNumber.toFixed(2))
Why not * the result by 1 i.e
someNumber.toFixed(2) * 1
Here's a slightly more functional version of the answer m93a provided.
const toFixedNumber = (toFixTo = 2, base = 10) => num => {
const pow = Math.pow(base, toFixTo)
return +(Math.round(num * pow) / pow)
}
const oneNumber = 10.12323223
const result1 = toFixedNumber(2)(oneNumber) // 10.12
const result2 = toFixedNumber(3)(oneNumber) // 10.123
// or using pipeline-operator
const result3 = oneNumber |> toFixedNumber(2) // 10.12
For others like me that happen upon this very old question, a modern solution:
const roundValue = (num, decimals = 2) => {
let scaling = 10 ** decimals;
return Math.round((num + Number.EPSILON) * scaling) / scaling;
}
ref: https://stackoverflow.com/a/11832950
Be careful using toFixed() and Math.round(), they can produce unexpected results due to the floating point number system:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
console.log(toFixedNumber(130.795, 2, 10));
// 130.79 (incorrect)
console.log(toFixedNumber(100.795, 2, 10));
// 100.8
console.log(+130.795.toFixed(2));
// 130.79 (incorrect)
console.log(+100.795.toFixed(2));
// 100.8
I recommend using Lodash's _.round() function: https://lodash.com/docs/4.17.15#round
_.round(130.795, 2);
// 130.8

Categories

Resources