How to round float numbers in javascript? - javascript

I need to round for example 6.688689 to 6.7, but it always shows me 7.
My method:
Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or
Math.round(6.688689, 2);
But result always is the same 7... What am I doing wrong?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Upd (2019-10). Thanks to Reece Daniels code below now available as a set of functions packed in npm-package expected-round (take a look).
You can use helper function from MDN example. Than you'll have more flexibility:
Math.round10(5.25, 0); // 5
Math.round10(5.25, -1); // 5.3
Math.round10(5.25, -2); // 5.25
Math.round10(5, 0); // 5
Math.round10(5, -1); // 5
Math.round10(5, -2); // 5
Upd (2019-01-15). Seems like MDN docs no longer have this helper funcs. Here's a backup with examples:
// Closure
(function() {
/**
* Decimal adjustment of a number.
*
* #param {String} type The type of adjustment.
* #param {Number} value The number.
* #param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
* #returns {Number} The adjusted value.
*/
function decimalAdjust(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// If the value is negative...
if (value < 0) {
return -decimalAdjust(type, -value, exp);
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
// Decimal round
if (!Math.round10) {
Math.round10 = function(value, exp) {
return decimalAdjust('round', value, exp);
};
}
// Decimal floor
if (!Math.floor10) {
Math.floor10 = function(value, exp) {
return decimalAdjust('floor', value, exp);
};
}
// Decimal ceil
if (!Math.ceil10) {
Math.ceil10 = function(value, exp) {
return decimalAdjust('ceil', value, exp);
};
}
})();
Usage examples:
// Round
Math.round10(55.55, -1); // 55.6
Math.round10(55.549, -1); // 55.5
Math.round10(55, 1); // 60
Math.round10(54.9, 1); // 50
Math.round10(-55.55, -1); // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1); // -50
Math.round10(-55.1, 1); // -60
Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2); // -1.01
// Floor
Math.floor10(55.59, -1); // 55.5
Math.floor10(59, 1); // 50
Math.floor10(-55.51, -1); // -55.6
Math.floor10(-51, 1); // -60
// Ceil
Math.ceil10(55.51, -1); // 55.6
Math.ceil10(51, 1); // 60
Math.ceil10(-55.59, -1); // -55.5
Math.ceil10(-59, 1); // -50

> +(6.688687).toPrecision(2)
6.7
A Number object in JavaScript has a method that does exactly what you need. That method is Number.toPrecision([precision]).
Just like with .toFixed(1) it converts the result into a string, and it needs to be converted back into a number. Done using the + prefix here.
simple benchmark on my laptop:
number = 25.645234 typeof number
50000000 x number.toFixed(1) = 25.6 typeof string / 17527ms
50000000 x +(number.toFixed(1)) = 25.6 typeof number / 23764ms
50000000 x number.toPrecision(3) = 25.6 typeof string / 10100ms
50000000 x +(number.toPrecision(3)) = 25.6 typeof number / 18492ms
50000000 x Math.round(number*10)/10 = 25.6 typeof number / 58ms
string = 25.645234 typeof string
50000000 x Math.round(string*10)/10 = 25.6 typeof number / 7109ms

If you not only want to use toFixed() but also ceil() and floor() on a float then you can use the following function:
function roundUsing(func, number, prec) {
var tempnumber = number * Math.pow(10, prec);
tempnumber = func(tempnumber);
return tempnumber / Math.pow(10, prec);
}
Produces:
> roundUsing(Math.floor, 0.99999999, 3)
0.999
> roundUsing(Math.ceil, 0.1111111, 3)
0.112
UPD:
The other possible way is this:
Number.prototype.roundUsing = function(func, prec){
var temp = this * Math.pow(10, prec)
temp = func(temp);
return temp / Math.pow(10, prec)
}
Produces:
> 6.688689.roundUsing(Math.ceil, 1)
6.7
> 6.688689.roundUsing(Math.round, 1)
6.7
> 6.688689.roundUsing(Math.floor, 1)
6.6

My extended round function:
function round(value, precision) {
if (Number.isInteger(precision)) {
var shift = Math.pow(10, precision);
// Limited preventing decimal issue
return (Math.round( value * shift + 0.00000000000001 ) / shift);
} else {
return Math.round(value);
}
}
Example Output:
round(123.688689) // 123
round(123.688689, 0) // 123
round(123.688689, 1) // 123.7
round(123.688689, 2) // 123.69
round(123.688689, -2) // 100
round(1.015, 2) // 1.02

See below
var original = 28.59;
var result=Math.round(original*10)/10 will return you returns 28.6
Hope this is what you want..

There is the alternative .toLocaleString() to format numbers, with a lot of options regarding locales, grouping, currency formatting, notations. Some examples:
Round to 1 decimal, return a float:
const n = +6.688689.toLocaleString('fullwide', {maximumFractionDigits:1})
console.log(
n, typeof n
)
Round to 2 decimals, format as currency with specified symbol, use comma grouping for thousands:
console.log(
68766.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'currency', currency:'USD', useGrouping:true})
)
Format as locale currency:
console.log(
68766.688689.toLocaleString('fr-FR', {maximumFractionDigits:2, style:'currency', currency:'EUR'})
)
Round to minimum 3 decimal, force zeroes to display:
console.log(
6.000000.toLocaleString('fullwide', {minimumFractionDigits:3})
)
Percent style for ratios. Input * 100 with % sign
console.log(
6.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'})
)

I have very good solution with if toFixed() is not working.
function roundOff(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
Example
roundOff(10.456,2) //output 10.46

float(value,ndec);
function float(num,x){
this.num=num;
this.x=x;
var p=Math.pow(10,this.x);
return (Math.round((this.num).toFixed(this.x)*p))/p;
}

+((6.688689 * (1 + Number.EPSILON)).toFixed(1)); // 6.7
+((456.1235 * (1 + Number.EPSILON)).toFixed(3)); // 456.124

I think this function can help.
function round(value, ndec){
var n = 10;
for(var i = 1; i < ndec; i++){
n *=10;
}
if(!ndec || ndec <= 0)
return Math.round(value);
else
return Math.round(value * n) / n;
}
round(2.245, 2) //2.25
round(2.245, 0) //2

if you're under node.js context, you can try mathjs
const math = require('mathjs')
math.round(3.1415926, 2)
// result: 3.14

Math.round((6.688689 + Number.EPSILON) * 10) / 10
Solution stolen from https://stackoverflow.com/a/11832950/2443681
This should work with nearly any float value. It doesn't force decimal count though. It's not clear whether this was a requirement. Should be faster than using toFixed(), which has other issues as well based on the comments to other answers.
A nice utility function to round in needed decimal precision:
const roundToPrecision = (value, decimals) => {
const pow = Math.pow(10, decimals);
return Math.round((value + Number.EPSILON) * pow) / pow;
};

I think below function can help
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
usage : roundOff(600.23458,2); will return 600.23

Minor tweak to this answer:
function roundToStep(value, stepParam) {
var step = stepParam || 1.0;
var inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55
roundToStep(2, 0.01) = 2

How to correctly round decimals in a number (basics):
We start from far right number:
If this number is >= to 5 rounding is required, we will then report a 1 to the first number on the left.
If this number is < to 5 means no rounding
Once you know if you need to report a value or not you can delete the last number and repeat the operation.
If there is a value to be reported you will first add it to the new far right number before repeating the previous tests.
Beware there is a special case when you need to report a value and the number that must be added to that value is 9 : in such case you will have to change the number value for 0 before reporting a 1 on the following left number.
For some of the failing answers it looks like decimals are splitted left to right for the required amount of decimals without even caring about the rounding.
Now that this is stated here is a function that will round a provided float value recursively using the above logic.
function roundFloatR(n, precision = 0, opts = { return: 'number' }) { // Use recursivity
if ( precision == 0 ) { // n will be rounded to the closest integer
if (opts.return == 'number') return Math.round(n);
else if (opts.return == 'string') return `${Math.round(n)}`;
} else {
let ns = `${n}`.split(''); // turns float into a string before splitting it into a char array
if ( precision < 0 ) { // precision is a negative number
precision += ns.length - 1; // precision equals last index of ns - its actual value
} else if ( precision > 0 ) { // precision is a positive number
if ( ns.indexOf('.') > -1 )
precision += ns.indexOf('.'); // precision equals its value + the index of the float separator in the string / array of char
}
// RECURSIVE FUNCTION: loop from the end of ns to the precision index while rounding the values
// index: index in the ns char array, rep: reported value, (INTERNAL_VAR, cn: current number)
const recursive = (index, rep) => {
let cn = parseInt(ns[index]); // get the current number from ns at index
if (index <= precision) { // current index inferior or equal to the defined precision index (end of rounding)
if (rep) { // if a reported value exists
cn += rep; // add reported value to current number
if (cn == 10) { // extends rounding for special case of decimals ending with 9 + reported value
ns[index] = '0';
recursive( (index - 1), 1 ); // calls recursive() again with a reported value
} else if (cn < 10)
ns[index] = `${cn}`;
}
} else if (index > precision) { // current index superior to defined precision index
ns.pop(); // each passage in this block will remove the last entry of ns
if (rep) cn += rep; // adds reported value (if it exists) to current number
if ( cn >= 5 ) // ROUNDING
recursive( (index - 1), 1 ); // calls recursive() again with a reported value
else // NO ROUNDING
recursive( index - 1 ); // calls recursive() again w/o a reported value
}
}; // end of recursive()
recursive(ns.length - 1); // starts recursive rounding over the ns char array (arg is the last index of ns)
if (opts.return == "number") return parseFloat(ns.join('')); // returns float number
else if (opts.return == "string") return ns.join(''); // returns float number as string
}
} //
How it works:
We first turn the provided float value into a string before splitting it into an array of char using the String.split('') instruction.
Then we will call the recursive() function with the last index of the array of chars as argument, to iterate through that array from last index to the precision index while rounding the value.
Arguments explanation:
There is a total of 3 arguments which allow different functionnalities.
n:
the value to be rounded (number or string).
precision: [default = 0]
an int which represent the amount of decimals we want to round the provided number to.
There are 3 possibilities:
precision == 0: value returned will be the same as using the Math.round() method
precision > 0: precision will be defined from the float separator index + precision value
precision < 0: precision will be defined from the index of the last number - precision value
opts: [default = {return: 'number'}]
an options object with a unique property called return which take a string value options are 'number' or 'string'. allows the selection of the type of value returned by the function
2nd and 3rd arguments are optionnals
Usage and examples:
using a float value
let n = 20.336099982261654;
let r = roundFloatR(n); // r = 20
r = roundFloatR(n, 2); // r = 20.34
r = roundFloatR(n, 6); // r = 20.3361
r = roundFloatR(n, 6, {return: 'string'}); // r = "20.336100"
// negative precision
r = roundFloatR(n, -2); // r = 20.3360999822617
using a string value
let n = '20.48490002346038';
let r = roundFloatR(n); // r = 20
r = roundFloatR(n, 2); // r = 20.49
r = roundFloatR(n, 6); // r = 20.4849
r = roundFloatR(n, 6, {return: 'string'}); // r = "20.484900"
// negative precision
r = roundFloatR(n, -10); // r = 20.4849
What about performance ?
Most of the time it will convert the provided value in under .3 ms. (measured with performance.now())
What is not supported and possible issues:
not supported: exponential type values some changes may be required to support them.
possible issues:
a negative precision value that exceeds the provided number length or its float separator index may cause unexpected results as these cases are not handled yet.
no error handling in case the n parameter doesn't match what is currently asked.

If you're using Browserify today, you're going to have to try: roundTo a very useful NPM lib

Related

convert decimal number to fraction in javascript or closest fraction [duplicate]

This question already has answers here:
How to simplify a decimal into the smallest possible fraction?
(6 answers)
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
So i want to be able to convert any decimal number into fraction. In both forms such as one without remainder like this: 3/5 or with remainder: 3 1/4.
what i was doing is this..
lets say i have number .3435.
Calculate amount of digits after decimals.
multiply by 10 with power of the amount before number.
then somehow find greatest common factor.
Now i don't know how to find GCF. And nor i know how to implement logic to find fraction that represents a number closely or in remainder form if exact fraction doesn't exists.
code i have so far: (testing)
x = 34/35;
a = x - x.toFixed();
tens = (10).pow(a.toString().length - 2);
numerator = tens * x;
denominator = tens;
Your first 2 steps are reasonable.
But what you should do is for the numerator and denominator calculate the Greatest Common Divisor (GCD) and then divide the numerator and denominator with that divisor to get the fraction you want.
GCD is rather easy to calculate. Here is Euclid's algorithm:
var gcd = function(a, b) {
if (!b) return a;
return gcd(b, a % b);
};
Edit
I've added a fully working JSFiddle.
Unless you are willing to work on developing something yourself then I would suggest using a library that someone has already put effort into, like fraction.js
Javascript
var frac = new Fraction(0.3435);
console.log(frac.toString());
Output
687/2000
On jsFiddle
You can use brute force test on different denominators and retain the result that has least error.
The algorithm below is an example of how you might go about this, but, suffers from being inefficient and limited to searching for denominators up to 10000.
function find_rational( value, maxdenom ) {
console.clear();
console.log( "Looking up: " + value );
let best = { numerator: 1, denominator: 1, error: Math.abs(value - 1) }
if ( !maxdenom ) maxdenom = 10000;
for ( let denominator = 1; best.error > 0 && denominator <= maxdenom; denominator++ ) {
let numerator = Math.round( value * denominator );
let error = Math.abs( value - numerator / denominator );
if ( error >= best.error ) continue;
best.numerator = numerator;
best.denominator = denominator;
best.error = error;
console.log( "Intermediate result: "
+ best.numerator + "/" + best.denominator
+ " (" + ( best.numerator/best.denominator)
+ " error " + best.error + " )" );
}
console.log( "Final result: " + JSON.stringify( best ) );
return best;
}
function calc() {
const value = parseFloat( $("#myInput").val() );
if ( isNaN(value) ) {
$( "#myResult" ).val( "NaN" );
return;
}
const rational = find_rational( value, 10000 );
$("#myResult").val( rational.numerator
+ " / " + rational.denominator
+ " ( Error: " + rational.error + " )" );
}
calc();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<P>
Enter a decimal number:<BR/>
<INPUT type="text" name="myInput" id="myInput" value=".3435" onkeyup="calc()"/><BR/>
</P>
<P>
Resulting Rational:<BR/>
<INPUT name="myResult" id="myResult" value=""/><BR/>
</P>
The above determines the .3435 as a fraction is 687 / 2000.
Also, had you gave it PI (e.g. 3.1415926) it produces good looking fractions like 22/7 and 355/113.
One quick and easy way of doing it is
getFraction = (decimal) => {
for(var denominator = 1; (decimal * denominator) % 1 !== 0; denominator++);
return {numerator: decimal * denominator, denominator: denominator};
}
I get very poor results using the GCD approach. I got much better results using an iterative approach.
For example, here is a very crude approach that zeros in on a fraction from a decimal:
function toFraction(x, tolerance) {
if (x == 0) return [0, 1];
if (x < 0) x = -x;
if (!tolerance) tolerance = 0.0001;
var num = 1, den = 1;
function iterate() {
var R = num/den;
if (Math.abs((R-x)/x) < tolerance) return;
if (R < x) num++;
else den++;
iterate();
}
iterate();
return [num, den];
}
The idea is you increment the numerator if you are below the value, and increment the denominator if you are above the value.
Use the Euclidean algorithm to find the greatest common divisor.
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return [numerator/gcd, denominator/gcd];
}
This will provide you with the following results on your console
reduce(2,4);
// [1,2]
reduce(13427,3413358);
// [463,117702]
So by continuing from already what you have,
var x = 34/35;
var a = x - x.toFixed();
var tens = Math.pow(10,a.toString().length - 2);
var numerator = tens * x;
var denominator = tens;
reduce(numerator,denominator);
Source: https://stackoverflow.com/a/4652513/1998725
I had researched all over the website and I did combine all code into one, Here you go!
function fra_to_dec(num){
var test=(String(num).split('.')[1] || []).length;
var num=(num*(10**Number(test)))
var den=(10**Number(test))
function reduce(numerator,denominator){
var gcd = function gcd(a,b) {
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return [numerator/gcd, denominator/gcd];
}
return (reduce(num,den)[0]+"/"+reduce(num,den)[1])
}
This code is very easy to use! You can even put number in this function!
The tricky bit is not letting floating points get carried away.
Converting a number to a string restrains the trailing digits,
especially when you have a decimal with an integer, like 1.0625.
You can round off clumsy fractions, by passing a precision parameter.
Often you want to force a rounded value up, so a third parameter can specify that.
(e.g.; If you are using a precision of 1/64, the smallest return for a non-zero number will be 1/64, and not 0.)
Math.gcd= function(a, b){
if(b) return Math.gcd(b, a%b);
return Math.abs(a);
}
Math.fraction= function(n, prec, up){
var s= String(n),
p= s.indexOf('.');
if(p== -1) return s;
var i= Math.floor(n) || '',
dec= s.substring(p),
m= prec || Math.pow(10, dec.length-1),
num= up=== 1? Math.ceil(dec*m): Math.round(dec*m),
den= m,
g= Math.gcd(num, den);
if(den/g==1) return String(i+(num/g));
if(i) i= i+' and ';
return i+ String(num/g)+'/'+String(den/g);
}
Math.roundFraction(.3435,64); value: (String) 11/32
Inspired by #chowey answer, which contained recursive implementation of finding close fraction for a decimal value within given tolerance, here is better (see benchmark), iterative version of it.
function toFractionIterative(x, epsilon = 0.0001) {
if (x == 0) return [0, 1];
const a = Math.abs(x);
let n = 0;
let d = 1;
let r;
while (true) {
r = n / d;
if (Math.abs((r - a) / a) < epsilon) {
break;
}
if (r < a) {
n++;
}
else {
d++;
}
}
return [x < 0 ? -n : n, d];
}
Benchmark (tl;dr: recursive 1,589 ops/s, iterative 5,955 ops/s; use iterative approach)
let v = 3.141592;
document.write(d2f(v)); // 392699/125000
function d2f(v) // decimal to fraction
{
if (Math.floor(v) == v) return v + '/' + 1;
v = Math.abs(v);
let ret = .01, // rounding error tolerance
td = v-Math.floor(v), // trailing digits
r = 1/td, // reciprocal
d = r, // start building denominator
lim = 20; // max loop limit
for (let i = 0; i < lim; i++)
{
td = r-Math.floor(r);
if (Math.abs(r-Math.round(r)) < ret) break;
r = 1/td;
d *= r;
}
return Math.round(d*v) + '/' + Math.round(d);
}
I came up with this for 16ths
function getfract(theNum){
var input=theNum.toString();
var whole = input.split(".")[0];
var rem = input.split(".")[1] * .1;
return(whole + " " + Math.round(rem * 16) + "/16");
}
function decimalToFraction(num) {
let numsAfterDecPoint = num.toString().split('.')[1] ? num.toString().split('.')[1].length : 0;
let numerator = num * Math.pow(10, numsAfterDecPoint);
let denominator = Math.pow(10, numsAfterDecPoint);
console.log(numerator + " / " + denominator)
let d = GCD(numerator,denominator)
return numerator / d + " / " + denominator / d
}
console.log(decimalToFraction(0.5)); // 5 / 10 => 1 / 2
console.log(decimalToFraction(178.45)); // 17845 / 100 => 3569 / 20
function GCD(a,b) {
let r = 0;
while(b != 0) {
r = a % b
a = b;
b = r;
}
return a;
}

How to convert the last 3 digits of the number?

How to convert the last 3 digits of the number? Numbers will be bigger then 8000.
For example:
From 249439 to 249000?
You can get the last three digits using the modulus operator %, which (for positive numbers) computes the remainder after integer division; for example, 249439 % 1000 is 439.
So to round down to the nearest thousand, you can just subtract those three digits:
var rounded = original - original % 1000;
(for example, if original is 249439, then rounded will be 249000).
I'd suggest the following:
function roundLastNDigits (num, digits) {
// making sure the variables exist, and are numbers; if *not* we quit at this point:
if (!num || !parseInt(num,10) || !digits || !parseInt(digits,10)) {
return false;
}
else {
/* otherwise we:
- divide the number by 10 raised to the number of digits
(to shift divide the number so that those digits follow
the decimal point), then
- we round that number, then
- multiply by ten raised to the number of digits (to
recreate the same 'size' number/restoring the decimal fraction
to an integer 'portion' */
return Math.round(num / Math.pow(10, parseInt(digits,10))) * Math.pow(10,digits);
}
}
console.log(roundLastNDigits(249439, 3))
JS Fiddle demo.
If you'd prefer to always round down, I'd amend the above to give:
function roundLastNDigits (num, digits) {
if (!num || !parseInt(num,10) || !digits || !parseInt(digits,10)) {
return false;
}
else {
return Math.floor(num / Math.pow(10, parseInt(digits,10))) * Math.pow(10,digits);
}
}
console.log(roundLastNDigits(8501, 3))
JS Fiddle demo.
Simplifying the above by incorporating ruakh's genius approach:
function roundLastNDigits (num, digits) {
if (!num || !parseInt(num,10) || !digits || !parseInt(digits,10)) {
return false;
}
else {
return num - (num % Math.pow(10,parseInt(digits,10)));
}
}
console.log(roundLastNDigits(8501, 3))
JS Fiddle demo.
Or, finally, given that you only need to replace the last three digit characters with 0:
function roundLastNDigits (num, digits) {
if (!num || !digits || !parseInt(digits,10)) {
return false;
}
else {
var reg = new RegExp('\\d{' + digits + '}$');
return num.toString().replace(reg, function (a) {
return new Array(parseInt(digits,10) + 1).join(0);
});
}
}
console.log(roundLastNDigits(8501, 3))
JS Fiddle demo.
References:
Math.floor().
Math.pow().
Math.round().
parseInt().
For always rounding down I'd suggest dividing out 1000, casting to Int then multipling back in 1000
var x = 249439,
y = ((x / 1000) | 0) * 1000; // 249000
1)
Math.round(num.toPrecision(3));
This doesn't account for the values before the 3rd value to round.
2)
This is sort of a bad solution but it works.
num = 50343 // whatever your input is.
m = 10^n.
Math.round(num*m)/m
n being the amount you want to move over.

Adding Decimal place into number with javascript

I've got this number as a integer 439980
and I'd like to place a decimal place in 2 places from the right. to make it 4399.80
the number of characters can change any time, so i always need it to be 2 decimal places from the right.
how would I go about this?
thanks
function insertDecimal(num) {
return (num / 100).toFixed(2);
}
Just adding that toFixed() will return a string value, so if you need an integer it will require 1 more filter. You can actually just wrap the return value from nnnnnn's function with Number() to get an integer back:
function insertDecimal(num) {
return Number((num / 100).toFixed(2));
}
insertDecimal(99552) //995.52
insertDecimal("501") //5.01
The only issue here is that JS will remove trailing '0's, so 439980 will return 4399.8, rather than 4399.80 as you might hope:
insertDecimal(500); //5
If you're just printing the results then nnnnnn's original version works perfectly!
notes
JavaScript's Number function can result in some very unexpected return values for certain inputs. You can forgo the call to Number and coerce the string value to an integer by using unary operators
return +(num / 100).toFixed(2);
or multiplying by 1 e.g.
return (num / 100).toFixed(2) * 1;
TIL: JavaScript's core math system is kind of weird
Another Method
function makeDecimal(num){
var leftDecimal = num.toString().replace('.', ''),
rightDecimal = '00';
if(leftDecimal.length > 2){
rightDecimal = leftDecimal.slice(-2);
leftDecimal = leftDecimal.slice(0, -2);
}
var n = Number(leftDecimal+'.'+rightDecimal).toFixed(2);
return (n === "NaN") ? num:n
}
makeDecimal(3) // 3.00
makeDecimal(32) // 32.00
makeDecimal(334) // 3.34
makeDecimal(13e+1) // 1.30
Or
function addDecimal(num){
var n = num.toString();
var n = n.split('.');
if(n[1] == undefined){
n[1] = '00';
}
if(n[1].length == 1){
n[1] = n[1]+'0';
}
return n[0]+'.'+n[1];
}
addDecimal(1); // 1.00
addDecimal(11); // 11.00
addDecimal(111); // 111.00
Convert Numbers to money.
function makeMoney(n){
var num = n.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
One More.
function addDecimal(n){
return parseFloat(Math.round(n * 100) / 100).toFixed(2);
}

Converting hexadecimal to float in JavaScript

I would like to convert a number in base 10 with fraction to a number in base 16.
var myno = 28.5;
var convno = myno.toString(16);
alert(convno);
All is well there. Now I want to convert it back to decimal.
But now I cannot write:
var orgno = parseInt(convno, 16);
alert(orgno);
As it doesn't return the decimal part.
And I cannot use parseFloat, since per MDC, the syntax of parseFloat is
parseFloat(str);
It wouldn't have been a problem if I had to convert back to int, since parseInt's syntax is
parseInt(str [, radix]);
So what is an alternative for this?
Disclaimer: I thought it was a trivial question, but googling didn't give me any answers.
This question made me ask the above question.
Another possibility is to parse the digits separately, splitting the string up in two and treating both parts as ints during the conversion and then add them back together.
function parseFloat(str, radix)
{
var parts = str.split(".");
if ( parts.length > 1 )
{
return parseInt(parts[0], radix) + parseInt(parts[1], radix) / Math.pow(radix, parts[1].length);
}
return parseInt(parts[0], radix);
}
var myno = 28.4382;
var convno = myno.toString(16);
var f = parseFloat(convno, 16);
console.log(myno + " -> " + convno + " -> " + f);
Try this.
The string may be raw data (simple text) with four characters (0 - 255) or
a hex string "0xFFFFFFFF" four bytes in length.
jsfiddle.net
var str = '0x3F160008';
function parseFloat(str) {
var float = 0, sign, order, mantissa, exp,
int = 0, multi = 1;
if (/^0x/.exec(str)) {
int = parseInt(str, 16);
}
else {
for (var i = str.length -1; i >=0; i -= 1) {
if (str.charCodeAt(i) > 255) {
console.log('Wrong string parameter');
return false;
}
int += str.charCodeAt(i) * multi;
multi *= 256;
}
}
sign = (int >>> 31) ? -1 : 1;
exp = (int >>> 23 & 0xff) - 127;
mantissa = ((int & 0x7fffff) + 0x800000).toString(2);
for (i=0; i<mantissa.length; i+=1) {
float += parseInt(mantissa[i]) ? Math.pow(2, exp) : 0;
exp--;
}
return float*sign;
}
Please try this:
function hex2dec(hex) {
hex = hex.split(/\./);
var len = hex[1].length;
hex[1] = parseInt(hex[1], 16);
hex[1] *= Math.pow(16, -len);
return parseInt(hex[0], 16) + hex[1];
}
function hex2dec(hex) {
hex = hex.split(/\./);
var len = hex[1].length;
hex[1] = parseInt(hex[1], 16);
hex[1] *= Math.pow(16, -len);
return parseInt(hex[0], 16) + hex[1];
}
// ----------
// TEST
// ----------
function calc(hex) {
let dec = hex2dec(hex);
msg.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${dec.toString(16)}</b>`
}
let init="bad.a55";
inp.value=init;
calc(init);
<input oninput="calc(this.value)" id="inp" /><div id="msg"></div>
I combined Mark's and Kent's answers to make an overloaded parseFloat function that takes an argument for the radix (much simpler and more versatile):
function parseFloat(string, radix)
{
// Split the string at the decimal point
string = string.split(/\./);
// If there is nothing before the decimal point, make it 0
if (string[0] == '') {
string[0] = "0";
}
// If there was a decimal point & something after it
if (string.length > 1 && string[1] != '') {
var fractionLength = string[1].length;
string[1] = parseInt(string[1], radix);
string[1] *= Math.pow(radix, -fractionLength);
return parseInt(string[0], radix) + string[1];
}
// If there wasn't a decimal point or there was but nothing was after it
return parseInt(string[0], radix);
}
Try this:
Decide how many digits of precision you need after the decimal point.
Multiply your original number by that power of 16 (e.g. 256 if you want two digits).
Convert it as an integer.
Put the decimal point in manually according to what you decided in step 1.
Reverse the steps to convert back.
Take out the decimal point, remembering where it was.
Convert the hex to decimal in integer form.
Divide the result by the the appropriate power of 16 (16^n, where n is the number of digits after the decimal point you took out in step 1).
A simple example:
Convert decimal 23.5 into hex, and want one digit after the decimal point after conversion.
23.5 x 16 = 376.
Converted to hex = 0x178.
Answer in base 16: 17.8
Now convert back to decimal:
Take out the decimal point: 0x178
Convert to decimal: 376
Divide by 16: 23.5
I'm not sure what hexadecimal format you wanted to parse there. Was this something like: "a1.2c"?
Floats are commonly stored in hexadecimal format using the IEEE 754 standard. That standard doesn't use any dots (which don't exist in pure hexadecimal alphabet). Instead of that there are three groups of bits of predefined length (1 + 8 + 23 = 32 bits in total ─ double uses 64 bits).
I've written the following function for parsing such a numbers into float:
function hex2float(num) {
var sign = (num & 0x80000000) ? -1 : 1;
var exponent = ((num >> 23) & 0xff) - 127;
var mantissa = 1 + ((num & 0x7fffff) / 0x7fffff);
return sign * mantissa * Math.pow(2, exponent);
}
Here is a size-improvement of Mark Eirich's answer:
function hex2dec(hex) {
let h = hex.split(/\./);
return ('0x'+h[1])*(16**-h[1].length)+ +('0x'+h[0]);
}
function hex2dec(hex) {
let h = hex.split(/\./);
return ('0x'+h[1])*(16**-h[1].length)+ +('0x'+h[0]);
}
function calc(hex) {
let dec = hex2dec(hex);
msg.innerHTML = `dec: <b>${dec}</b><br>hex test: <b>${dec.toString(16)}</b>`
}
let init = "bad.a55";
inp.value = init;
calc(init);
<input oninput="calc(this.value)" id="inp" /><div id="msg"></div>
private hexStringToFloat(hexString: string): number {
return Buffer.from(hexString, 'hex').readFloatBE(0);
}
Someone might find this useful.
bytes to Float32
function Int2Float32(bytes) {
var sign = (bytes & 0x80000000) ? -1 : 1;
var exponent = ((bytes >> 23) & 0xFF) - 127;
var significand = (bytes & ~(-1 << 23));
if (exponent == 128)
return sign * ((significand) ? Number.NaN : Number.POSITIVE_INFINITY);
if (exponent == -127) {
if (significand === 0) return sign * 0.0;
exponent = -126;
significand /= (1 << 22);
} else significand = (significand | (1 << 23)) / (1 << 23);
return sign * significand * Math.pow(2, exponent);
}

Gaussian/banker's rounding in JavaScript

I have been using Math.Round(myNumber, MidpointRounding.ToEven) in C# to do my server-side rounding, however, the user needs to know 'live' what the result of the server-side operation will be which means (avoiding an Ajax request) creating a JavaScript method to replicate the MidpointRounding.ToEven method used by C#.
MidpointRounding.ToEven is Gaussian/banker's rounding, a very common rounding method for accounting systems described here.
Does anyone have any experience with this? I have found examples online, but they do not round to a given number of decimal places...
function evenRound(num, decimalPlaces) {
var d = decimalPlaces || 0;
var m = Math.pow(10, d);
var n = +(d ? num * m : num).toFixed(8); // Avoid rounding errors
var i = Math.floor(n), f = n - i;
var e = 1e-8; // Allow for rounding errors in f
var r = (f > 0.5 - e && f < 0.5 + e) ?
((i % 2 == 0) ? i : i + 1) : Math.round(n);
return d ? r / m : r;
}
console.log( evenRound(1.5) ); // 2
console.log( evenRound(2.5) ); // 2
console.log( evenRound(1.535, 2) ); // 1.54
console.log( evenRound(1.525, 2) ); // 1.52
Live demo: http://jsfiddle.net/NbvBp/
For what looks like a more rigorous treatment of this (I've never used it), you could try this BigNumber implementation.
This is the unusual stackoverflow where the bottom answers are better than the accepted. Just cleaned up #xims solution and made a bit more legible:
function bankersRound(n, d=2) {
var x = n * Math.pow(10, d);
var r = Math.round(x);
var br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r-1) : r;
return br / Math.pow(10, d);
}
That's a great solution from #soegaard.
Here is a small change that makes it work for decimal points:
bankers_round(n:number, d:number=0) {
var x = n * Math.pow(10, d);
var r = Math.round(x);
var br = (((((x>0)?x:(-x))%1)===0.5)?(((0===(r%2)))?r:(r-1)):r);
return br / Math.pow(10, d);
}
And while at it - here are some tests:
console.log(" 1.5 -> 2 : ", bankers_round(1.5) );
console.log(" 2.5 -> 2 : ", bankers_round(2.5) );
console.log(" 1.535 -> 1.54 : ", bankers_round(1.535, 2) );
console.log(" 1.525 -> 1.52 : ", bankers_round(1.525, 2) );
console.log(" 0.5 -> 0 : ", bankers_round(0.5) );
console.log(" 1.5 -> 2 : ", bankers_round(1.5) );
console.log(" 0.4 -> 0 : ", bankers_round(0.4) );
console.log(" 0.6 -> 1 : ", bankers_round(0.6) );
console.log(" 1.4 -> 1 : ", bankers_round(1.4) );
console.log(" 1.6 -> 2 : ", bankers_round(1.6) );
console.log(" 23.5 -> 24 : ", bankers_round(23.5) );
console.log(" 24.5 -> 24 : ", bankers_round(24.5) );
console.log(" -23.5 -> -24 : ", bankers_round(-23.5) );
console.log(" -24.5 -> -24 : ", bankers_round(-24.5) );
The accepted answer does round to a given number of places. In the process it calls toFixed which converts the number to a string. Since this is expensive, I offer the solution below. It rounds a number ending in 0.5 to the nearest even number. It does not handle rounding to an arbitrary number of places.
function even_p(n){
return (0===(n%2));
};
function bankers_round(x){
var r = Math.round(x);
return (((((x>0)?x:(-x))%1)===0.5)?((even_p(r))?r:(r-1)):r);
};
I was not happy with the other answers. They have either too verbose or complicated code or fail to round properly for negative numbers. For negative numbers we have to cleverly fix a weird behavior of JavaScript:
JavaScript's Math.round has the unusual property that it rounds halfway cases towards positive infinity, regardless of whether they're positive or negative. So for example 2.5 will round to 3.0, but -2.5 will round to -2.0.
Source
This is wrong, so we have to round down on negatives .5 before applying the bankers rounding, accordantly.
Also, just as Math.round, I want to round to the next integer and enforce a precision of 0. I just want Math.round with the correct and fixed "round halves to even" method in positive and negative. It needs to round the same like in other programming languages such as PHP (PHP_ROUND_HALF_EVEN) or C# (MidpointRounding.ToEven).
/**
* Returns a supplied numeric expression rounded to the nearest integer while rounding halves to even.
*/
function roundMidpointToEven(x) {
const n = x >= 0 ? 1 : -1 // n describes the adjustment on an odd rounding from midpoint
const r = n * Math.round(n * x) // multiplying n will fix negative rounding
return Math.abs(x) % 1 === 0.5 && r % 2 !== 0 ? r - n : r // we adjust by n if we deal with a half on an odd rounded number
}
// testing by rounding cents:
for(let i = -10; i <= 10; i++) {
const val = i + .5
console.log(val + " => " + roundMidpointToEven(val))
}
Math.round as well as our custom roundMidpointToEven function won't care for precision, because it's always better to calculate with cents to avoid float-point issues on any calculations anyways.
However, if you don't deal with cents you can simply multiply and divide the appropriate factor for the number of decimal placeholders in the same way you would do it for Math.round:
const usd = 9.225;
const fact = Math.pow(10, 2) // A precision of 2, so 100 is the factor
console.log(roundMidpointToEven(usd * fact) / fact) // outputs 9.22 instead of 9.23
To fully validate the custom roundMidpointToEven function, here is the same output using PHP with its official PHP_ROUND_HALF_EVEN as well as C# using MidpointRounding.ToEven:
for($i = -10; $i <= 10; $i++) {
$val = $i + .5;
echo $val . ' => ' . round($val, 0, PHP_ROUND_HALF_EVEN) . "<br />";
}
for(int i = -10; i <= 10; i++)
{
double val = i + .5;
Console.WriteLine(val + " => " + Math.Round(val, MidpointRounding.ToEven));
}
Both snippets return the same like the test call of our custom roundMidpointToEven:
-9.5 => -10
-8.5 => -8
-7.5 => -8
-6.5 => -6
-5.5 => -6
-4.5 => -4
-3.5 => -4
-2.5 => -2
-1.5 => -2
-0.5 => 0
0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6
7.5 => 8
8.5 => 8
9.5 => 10
10.5 => 10
Success!
const isEven = (value: number) => value % 2 === 0;
const isHalf = (value: number) => {
const epsilon = 1e-8;
const remainder = Math.abs(value) % 1;
return remainder > .5 - epsilon && remainder < .5 + epsilon;
};
const roundHalfToEvenShifted = (value: number, factor: number) => {
const shifted = value * factor;
const rounded = Math.round(shifted);
const modifier = value < 0 ? -1 : 1;
return !isEven(rounded) && isHalf(shifted) ? rounded - modifier : rounded;
};
const roundHalfToEven = (digits: number, unshift: boolean) => {
const factor = 10 ** digits;
return unshift
? (value: number) => roundHalfToEvenShifted(value, factor) / factor
: (value: number) => roundHalfToEvenShifted(value, factor);
};
const roundDollarsToCents = roundHalfToEven(2, false);
const roundCurrency = roundHalfToEven(2, true);
If you do not like the overhead of calling toFixed()
Want to be able to supply an arbitrary scale
Don't want to introduce floating-point errors
Want to have readable, reusable code
roundHalfToEven is a function that generates a fixed scale rounding function. I do my currency operations on cents, rather than dollars, to avoid introducing FPEs. The unshift param exists to avoid the overhead of unshifting and shifting again for those operations.
Stricly speaking, all of these implementations should handle the case of a negative number of digits to round to.
It is an edge case, but still it would be wise to disallow it (or be very clear about what that means, for example -2 is rounding to the nearest amount of hundreds).
This solution is slightly more elegant than any of the current answers. It handles rounding negative numbers and negative number of decimal places correct.
function bankersRound (value, nDec = 2) {
let x = value * Math.pow(10, nDec);
let r = Math.round(x);
return (Math.abs(x) % 1 === .5 ? r - (r % 2) : r) / Math.pow(10, nDec);
}
For folks who want to be able to read the code a little better, here's an alternative implementation that seems to work.
function bankersRound(n, decimalPlaces) {
// Create our multiplier for floating point precision issues.
const multiplier = Math.pow(10, decimalPlaces);
// Multiple by decimal places to avoid rounding issues w/ floats
const num = n * multiplier;
// Use standard rounding
const rounded = Math.round(num);
// Only odd numbers should be rounded
const shouldUseBankersRound = rounded % 2 !== 0;
// Subtract one to ensure the rounded number is even
const bankersRound = shouldUseBankersRound ? rounded - 1 : rounded;
// Return to original precision
return bankersRound / multiplier;
}
console.log(
bankersRound(1.5255, 2),
bankersRound(1.53543, 2),
bankersRound(1.54543, 2),
bankersRound(1.54543, 3),
bankersRound(1.53529, 4),
bankersRound(1.53529, 2),
bankersRound(4.5, 0),
bankersRound(5.5, 0),
bankersRound(0.045, 2),
bankersRound(0.055, 2)
);

Categories

Resources