How to keep '.00' - javascript

How to keep '.00' in Javascript? I currently have the string "123456789012.00";
I want to get the double 123456789012.00 to keep .00
toFixed(2) will return a string
parseFloat() will cast the .00
How can I do this?

A float uses the precision it needs (that's why it's called a "float" -- as in "floating point", the point has no fixed position).
If you want to display a float with the 2 significant digits (i.e. 2 digits after the point), you can use toFixed(2). That will not change the number, but will store it in a string with the number of digits you want to show.

You can use the toFixed() method to do this. The code below will log the result you want in the console of your browser.
var num = "123456789012.00";
console.log(parseFloat(num).toFixed(2));

Related

How can I handle float number correctly in JS?

In JS, I do have a float number which come from php as below:
var number = 2,206.00
In JS, I need to use parseFloat that number.
So I tried parseFloat(number), but its give only 2. So how can I get 2206.00 instead of 2?
Number.parseFloat is the same function object as globalThis.parseFloat.
If globalThis.parseFloat encounters a character other than:
a plus sign or,
a minus sign or,
a decimal point or,
an exponent (E or e)
...it returns the value up to that character, ignoring the invalid character and characters following it. A second decimal point also stops parsing.
So the following prints 2. And this seems to be your problem.
console.log(parseFloat('2,206.00')) // 2
Solution: use string manipulation to remove any commas from the number (really a String before parsing it.
console.log(parseFloat('2,206.00'.replaceAll(',', ''))) // 2206
If you need to store the value as a number but render it as a formatted string, you may need Number#toFixed to render the values after the decimal point:
console.log((2206).toFixed(2)) // '2206.00'
Final note: be careful about localization because some countries use commas for decimal points and decimal points for number grouping. As #t.niese says: store number values without localization, and then apply localization at the surface of your app. But that is a wider, more complicated topic.
You have to remove comma first and use parseFloat.
And about 2 decimal after dot, I see you use number_format($myNumber, 2) in PHP, so in JS, you use .toFixed(2).
var number = '2,206.00';
var result = parseFloat(number.replace(/,/g, '')).toFixed(2);
console.log(result);
First of all what you currently have most probably would trigger an Unexpected number error in JS.
It seems the generated value comes from the number_format() PHP function which returns a string. Moreover the var number variable should also be considered a string as we have a string format.
So firstly you should quote var number = '2,206.00' after that, you have to make the string float-like in order to parse it as float so we should replace , with empty string in order for the number to become 2206.00 number = number.replace(",",""). Lastly the parse should be done now in order to convert the float-like string to an actual float parseFloat(number).
Whole code:
var number = '2,206.00';
number.replace(",","");
number = parseFloat(number);
ok, basically you want a two decimal number after point like (20.03),
try this
parseFloat(number).toFixed(2)

Parsefloat with 2 decimals without losing function to do equations (not as string)

I've seen multiple topics regarding this question, but none seem to answer it.
I want to round a number to two decimals, but without losing the function to use it in equations. So it shouldn't be transformed to a string. This DOES NOT work for what I want: parseFloat("50").toFixed(2)
Does anyone know how to parseFloat with 2 decimals as a number?
Just parse it back to a float.
parseFloat(Number(1.2345).toFixed(2)); //1.23
In javascript a number cannot have trailing zeros. 2.5 is a correct but 2.50 is not, this is why toFixed returns a string, not a number.
The best way to handle what you need is to store the number as a number and let it round out to whatever it needs. Only when showing the number on the screen should you do the toFixed(2) method to transforms it into a string.
// js
const price = 7.999999
const reducedPrice = price * 0.8
const finalReductionPrice = reducedPrice / 2.666666
// html
<p>price {price.toFixed(2)</p>
<p>reducedPrice {reducedPrice.toFixed(2)</p>
<p>finalReductionPrice {finalReductionPrice.toFixed(2)</p>

Add trailing zeros to an integer without converting to string in JS?

I'm looking to add decimals to the end of my integer. As an example:
15 => 15.00
The problem with methods like toFixed is that it will convert it into a string. I've tried to use parseFloat() and Number() on the string, but it'll convert it back to an integer with no decimals.
Is this possible? If not, can someone explain to me the logic behind why this isn't possible?
EDIT: Welp the intent was to display the number as a number, but from the going consensus, it looks like the way the only way to go about it is to use a string. Found an answer on the why: https://stackoverflow.com/a/17811916/8869701
The problem you are finding is that all numbers in javascript are floats.
a = 0.1
typeof a # "number"
b = 1
typeof b # number
They are the same.
So there is no real way to convert to from an integer to a float.
This is the reason that all of the parseFloat etc are string methods for reading and writing numbers from strings. Even if you did have floats and integers, specifying the precision of a number only really makes sense when you are displaying it to a user, and for this purpose it will be converted to a string anyway.
Depending on your exact use case you will need to use strings if you want to display with a defined precision.
When working with numbers 15 and 15.00 are equal. It wouldn't make any sense to use memory to store those trailing or leading zeros.
If that information is needed it is usually for displaying purposes. In that case a string is the right choice.
In case you need that value again you can parse the string as a number.

Converting big number string to number

What way i can convert string with 16 digits and 2 fraction value to number ?
Currently when I try to convert Number('1234567890123456.12') will became to 1234567890123456. fraction values will be gone.
I just want to confirm without using any third party lib can i convert this string to number ?
Unfortunately not. Javascript represents it's numbers using double precision floating point numbers. At 16 digits, it will only be able to store the integer component and not the part after the decimal point. You will need a bignum library to use this value.
EDIT: for reference the biggest integer you can use in JavaScript is 9,007,199,254,740,991
EDIT2: Thanks to Jeremy you can use a library like bignumberJS.
Your number has too many algorisms, I've created an example that simulates in the first position of the array the maximum length possible in javascript.
var nums = [
"12345678910111.12",
"1.5323",
"-42.7789"
];
nums.forEach(function(n) {
console.log(parseFloat(n).toFixed(2));
});
https://jsfiddle.net/7zzz1qzt/
I have faced issue to convert 18 digit string number to number. It is convert all digit to 0 after 16 digit. I have apply below code. it is working fine for me.
[{"id":${id},"name":"${name}"}]

.tofixed(2) not working when substracting a result?

How can i substract the result i get from x without loosing a decimal place in an html input box??
So, lets say i have x=40.40 and i substract 25, the result should be 15.40 and i am getting 15.4 without that zero. How can i prevent loosing that extra decimal, if i necesarily want to substract that 25 without altering anything else?? (For y i get a 0 with no decimal places and i need 0.00)
document.getElementById("posx").value=(x.toFixed(2)-25.00);
document.getElementById("posy").value=(y1.toFixed(2)-(-2.45));
You'll have to toFixed it after the subtraction
document.getElementById("posx").value = (x - 25.00).toFixed(2);
toFixed converts the value to a string, as numbers don't have zero padding, only the decimals needed to correctly reflect the value of the number.
When you subtract a number from a string, you end up with a number, and as numbers only have the needed decimals, no zero padding, you get 15.4, and once again have to use toFixed to convert it to a string with the decimals you need.

Categories