How to limit decimal digits in JavaScript output? [duplicate] - javascript

This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 5 years ago.
When I am trying to calculate the values
My output has 15 digits in decimal values
Like if x=3
Then in output it is showing
5.196152422706632
But how can I limit it to
5.19615
How to limit decimal digits in output from 15 digits to 5 digits in JavaScript?
Here is my script:
<script>
function myFunction() {
var x = document.getElementById("phase").value;
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + Math.sqrt(3)*x + "volts";
}
</script>
How can I use this:
double number = 0.#############;
DecimalFormat numberFormat = new DecimalFormat("#.#####");

The toFixed method allows you to set the number of digits.
I would use it like this:
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + (Math.sqrt(3) * x).toFixed(5) + "volts";
Btw, java is a completely different language to javascript - you're not using it here

In javascript you can fix the no of digits you want to display after decimal by using the function - toFixed(n).
Here n specifies the no of digits to display after decimal.
<script>
function myFunction() {
var x = document.getElementById("phase").value;
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + (Math.sqrt(3)*x).toFixed(5) + "volts";
}
</script>

In java you can do it like this.
public static void main(String[] args)
{
String value = String.format("%.3f", Math.sqrt(3)*9);
System.out.println("Value with 3 decimals: " + value);
}
In javascript you should check this anwser.

Related

Rounding a Number variable in javascript [duplicate]

This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 6 years ago.
I have this code:
function sellByte() {
if (player.bytes >= 1) {
player.bytes = player.bytes - 1;
player.money = player.money + 0.10;
document.getElementById("bytes").innerHTML = "Bytes: " + player.bytes;
document.getElementById("money").innerHTML = "$" + player.money;
}
}
And whenever I sell a Byte my money value ends up looking like $10.00000003 or something along those lines, how would I go about rounding the money value UP every time this function is run?
Working with float numbers in JS is very tricky. My suggestion is to operate only with smaller units (cents instead of dollars) and then you will only deal with integers and will not have similar issues.
Use Math.round(player.money* 100) / 100 for 2 decimal rounding.
Use any of the following code
Math.round(num * 100) / 100
using fixed Method
var numb = 123.23454;
numb = numb.toFixed(2);
or you can refer following link for more help
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

How to make 1 + 1 = 2 instead of 1 + 1 = 11 [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 7 years ago.
I am trying to add the number mathematically, but it keeps adding the number after it.
It takes the id number (begen), then it gets the number inside another div (kacbegen).
var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (kacbegen + 1);
alert(toplam);
However, when doing the math (toplam), it alerts all the numbers.How to add the number mathematically ?
Convert it to number via adding a +:
var toplam = (+kacbegen + 1);
Unary plus (+)
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.
It looks like you're working with Strings (and thus a + b is the concatenation operator) when you want to be working with Number (so x + y would be addition)
Perform your favorite way to cast String to Number, e.g. a unary +x
var kacbegen = +$("#math" + begen).text();
You need to use parseInt to convert kacbegen, which is a String instance, to a Number:
var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (parseInt(kacbegen) + 1);
alert(toplam);
The + operator, when used with a String on either side, will serve as a concatenation, calling Number.prototype.toString on 1.
You need to cast the contents to a number:
var contents = $("#math" + begen).text();
var kacbegen = parseFloat(contents);
You use kacbegen as a string. Please use as a integer use parseInt(kacbegen) + 1

Javascript to turn 110,000 into 110K and not 0.11M [duplicate]

This question already has an answer here:
Format a javascript number with a Metric Prefix like 1.5K, 1M, 1G, etc [duplicate]
(1 answer)
Closed 7 years ago.
To start with you need...
function m(n,d){x=(''+n).length,p=Math.pow,d=p(10,d)
x-=x%3
return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}
Then calling like so...
// m( ANY NUMBER HERE or VAR LIKE I USE,HOW DECIMAL PLACES)
m(110000,2)
However instead of the above's result of 0.11M, I would like it to display 110k.
What you have there is an example of an overly optimized script, lets make it more developer friendly an readable
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+n).length;
decimalPlaces=Math.pow(10,d); //raise 10 to the number of decimal places
var modLen = numberLength - numberLength%3;
var sufix = sufixes[modLen/3];
return Math.round(rawNumber*decimalPlaces/decimalPlaces(10,modLen))/decimalPlaces+ sufix;
}
Now it's easier to work with. We can see the issue is that we need to adjust for when the string is divisible by 3, so lets fix that.
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+rawNumber).length;
decimalPlaces=Math.pow(10,decimalPlaces); //raise 10 to the number of decimal places
//THis is the change
//If the length is divisable by 3 take 3 off the length
var modLen = numberLength%3 == 0 ? numberLength - 3 - (numberLength%3) : numberLength - (numberLength%3);
console.log(modLen);
var sufix = sufixes[(modLen/3)]
console.log(sufix)
return Math.round(rawNumber*decimalPlaces/Math.pow(10,modLen))/decimalPlaces+ sufix;
}
$(document).ready(function(){
$("#result").html(metricPrefix(110000,2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>

Multiplication results in unusual decimal places [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?
I have a strange mathematical problem during a multiplication in javascript.
$(parent).find('#id_deals-' + i + '-quantity').val()
result -> 10
$(parent).find('#id_deals-' + i + '-price').val()
result -> 3.99
Both above mulltiplied like this:
$(parent).find('#id_deals-' + i + '-price').val() * $(parent).find('#id_deals-' + i + '-quantity').val()
result --> 39.900000000000006
Why is this happening? and what can I do to limit the decimal places to 2 digits only?
Is it maybe because 10 has to be 10.0 ? But how do I convert my value to this format automatically before the actual multiplication?
Update:
According to syazdani's answer, I have tried to implement bigdecimal as suggested:
It is not well documented, but I got it working like this:
function run(opts) {
var bd = {"BigDecimal":BigDecimal, "BigInteger":BigInteger, "RoundingMode":RoundingMode};
var result;
var ops = {'*': "multiply", '/': "divide", '+': "add", '-': "subtract"};
var a = new bd.BigDecimal("" + opts.a);
var b = new bd.BigDecimal("" + opts.b);
var op = ops[opts.op];
if (op == "divide") {
return a.divide(b, 300, bd.RoundingMode.HALF_UP());
} else {
return a[op].call(a, b);
}
}
function multiply(a, b){
return run({"a":a,"b":b,"op":"*"});
}
If you are working with currency (as it seems that you are given the "price" id), you may be better served by using a so called Big Number library (such as this one: https://github.com/iriscouch/bigdecimal.js) for your math to control the math (round up vs round down, etc.). It takes a bit more work to get everything right, but it is worthwhile to avoid the Office Space math scenario.
All javascript number are IEEE-754 double precision floating points numbers. That means that they suffer from round-off errors and imprecision.
All numbers in javascript are floating point numbers, based on IEEE754.
If you want to format one as a string with a fixed number of digits after the dot, use
var formattedNumber = v.toFixed(2); // this makes a string

Input field values not adding up correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript's Math broken?
I'm attempting to add up three input fields, each containing a value of 33.3 which should total 99.9, however they are totaling to 99.89999999999999
Could someone explain how this is happening. Below is my code. Thanks in advance.
$("#modify-funding input.percentCalc").sumValues()
$.fn.sumValues = function () {
var sum = 0;
this.each(function () {
sum += $(this).fieldVal();
});
return sum;
};
$.fn.fieldVal = function () {
var val;
if ($(this).is(':input')) {
val = $(this).val();
alert("val " + val);
} else {
val = $(this).text();
}
return parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
};
Welcome to the wonderful world of floating point numbers. Floating points are aproximations of the number you want to represent. Thus when you save a number as 33.3 it is around but not exactly 33.3 this error adds up after multiple operations. The best way to compare floats is to not test for equality but to test weather they are in a range.
Instead of
if(x == 99.9)
try
if(Math.abs(99.9 - x) < .1)
If you just want the string representation. You could try handing the floating point number as an integer. i.e. 33.3 equals 333 then when you are turning it back into a string you add the decimal back in where appropriate. This would be the best solution for your problem.

Categories