Round float to 2 decimals javascript - javascript

I have the problem that when i round a number to 2 decimals the parseFloat() function removes .00 from the number. I have tried
var num = parseFloat(Math.round(19 * 100) / 100).toFixed(2);
The return: num="19.00"
The return i need: num = 19.00
I know 19 = 19.00, but i am using a service that always require two decimals .00
The function returns a string with the right value. When i parse it to float the .00 is removed.

You cannot get 19.00 as float, only as string, because numbers always remove trailing zeros.
Maybe you can show us a bit more code to get an idea, there you need these trailing zeros?

Numbers do and can not hold information about their representation. They are only a numerical value.
When you display a number using window.alert, console.log or similar, you are not looking at a number, but at a string. Those display functions convert numbers to strings before displaying them. Number.toFixed also converts numbers into strings, with the difference being that it rounds them to two decimal places, so you end up with another representation of the same number.
What I am trying to say is that to display a number, you cannot get around converting it to a string. Whether you do it explicitly or the display function does it for you. When you send the number to the service that you are using, you are probably also sending a string (JSON, XML, etc. are always strings once you send them). If you need the value of the number for calculations, use it, then convert it in the end. No matter how, you have to do it in the end if you want those 0's at the end.

Related

how to return number as float number es6

Well, im trying to return all my number in a specific format
Number(parseFloat(number).toFixed(fractionalDigits || 2))
this works fine but in some cases fails, here are some result
1.111 returns "1.11" and after converting it to number it will be returned 1.11
as float which is right,
but 2.2 returns "2.20" and after converting it to number it will be 2.2 i need it to be 2.20 as float
100 returns "100.00" because of toFixed Function and after converting it to number it back to 100 i need it 100.00 but as float
how can i do that ?
You can't.
Floats are numeric values, and there is no numerical difference between 2.2 and 2.20.
When outputting a float, it is converted to a string for display, and that will be the number in its simplest form. That is, 2.2, since the trailing 0 has no significance.
You wouldn't want 00000002.20000000, would you? Leading zeroes are just as useless.
If you want trailing zeroes to be displayed, use toFixed(). That's what the function is for. What you have right now is converting some arbitrary input (which for all we know is already numerical) into a float, then from a float to a string with a fixed number of decimal places, then back to a float again. All you've achieved is to truncate the number.
For the result you want remove fractionDigits from parameter and remove the las should work
parseFloat(number).toFixed(2)
the external Number() was not required as you already parsed number as float.Hope it helps
what was happening was the Number function was removing unnecessary 0 that the toFixed was putting in.

String to number to 2 decimal places

I have a string "215.00".
I want to convert this to a number and when I do parseInt("215.00") it returns 215 as a number. I want it to be as a number 215.00.
To try and do this I did parseFloat("215.00").toFixed(2);, however this also returns a string. I have found many answers on here, but they all convert the number to a string. Does anyone know how to fix this?
Please see my code attempt below:
var number = "215.00";
parseFloat(number).toFixed(2);
I want to get 215.00 as opposed to "215.00"
I will post here this as an Answer, for future purpose.
If you want to represent the zeros on the right hand-side, you need to represent it as a string. Because the numerical value of 215.00 it is in fact 215, therefore it will not keep the two decimal places.
The parseFloat method would work for a number such as "215.01", where it would parse it to the numerical value of 215.01.

Regex to make nondecimal number decimal (add .00)

I have an user input where user can edit price of something. To leave data consistance I would like to manipulate with that string on front-end site.
What I want to do is:
1234 to 1234.00
12.3 to 12.30
12,3 to 12.30
1234.45 to 1234.45
So basicly,
Replace comma with dots
this should be done easy with somehing like:
str.replace(',', '.');
Add dots if number if not decimal and also always change number of digits on two(so add 0 if needed)
I try to do something like:
priceByUser = priceByUser.replace(/^\d*\.?\d*$/, "$1\.00");
unfortunately this really doesnt even work as I expected.
Is there a chance someone can help me to solve this issue?
Thanks
You could consider using a regular expression to replace your commas and periods with just decimal points and then parse the values as floats via parseFloat() then finally, use the toFixed(2) function to indicate that you want two decimal places :
// This will clean up your input (consolidating periods and commas), parse the result
// as a floating point number and then format that number to two decimal places
priceByUser = parseFloat(priceByUser.replace(/,/g,'.')).toFixed(2);
If you wanted an extra-level of validation, you could consider stripping out any non-digit or decimal places after this occurs :
// Sanitize
priceByUser = priceByUser.replace(/,/g,'.').replace(/[^\d\.]/g,'');
// Parse and format
priceByUser = Number(priceByUser).toFixed(2);
Example
You can see a working example here and and example of input/output below :

How can I parse a string as an integer and keep decimal places if they are zeros?

I have these strings: "59.50" & "30.00"
What I need to do is convert them to integers but keep the trailing zeros at the end to effectively return:
59.50
30.00
I've tried:
Math.round(59.50 * 1000) / 1000
Math.round(30.00 * 1000) / 1000
but ended up with
59.5
30
I'm assuming I need to use a different method than Math.round as this automatically chops off trailing zeros.
I need to keep these as integers as they need to be multiplied with other integers and keep two decimals points. T thought this would be fairly straight forward but after a lot of searching I can't seem to find a solution to exactly what I need.
Thanks!
Your premise is flawed. If you parse a number, you are converting it to its numerical representation, which by definition doesn't have trailing zeros.
A further flaw is that you seem to think you can multiply two numbers together and keep the same number of decimal places as the original numbers. That barely makes sense.
It sounds like this might be an XY Problem, and what you really want to do is just have two decimal places in your result.
If so, you can use .toFixed() for this:
var num = parseFloat("59.50");
var num2 = parseFloat("12.33");
var num3 = num * num2
console.log(num3.toFixed(2)); // 733.64
Whenever you want to display the value of the variable, use Number.prototype.toFixed(). This function takes one argument: the number of decimal places to keep. It returns a string, so do it right before viewing the value to the user.
console.log((123.4567).toFixed(2)); // logs "123.46" (rounded)
To keep the decimals - multiply the string by 1
example : "33.01" * 1 // equals to 33.01
Seems you are trying to retain the same floating point, so better solution will be some thing like
parseFloat(string).toFixed(string.split('.')[1].length);
If you want numbers with decimal points, you are not talking about integers (which are whole numbers) but floating point numbers.
In Javascript all numbers are represented as floating point numbers.
You don't need the trailing zeros to do calculations. As long as you've got all the significant digits, you're fine.
If you want to output your result with a given number of decimal values, you can use the toFixed method to transform your number into a formatted string:
var num = 1.5
var output = num.toFixed(2) // '1.50'
// the number is rounded
num = 1.234
output = num.toFixed(2) // '1.23'
num = 1.567
output = num.toFixed(2) // '1.57'
Here's a more detailed description of toFixed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Add comma separator to a value variable

I have read some thousand comma separator JavaScript question/answer but found it hard to apply it in practice. For example I have the variable
x = 10023871234981029898198264897123897.231241235
How will I separate it in thousands with commas? I want a function that not only works with that number of digits but more. Regardless of the number of digits the function I need has to separate the number in commas and leaving the digits after the decimal point as it is, Can anyone help? It has to work on number and turn it into string.
First of all, for such huge numbers you should use string format:
var x = "10023871234981029898198264897123897.231241235";
Otherwise, JavaScript will automatically convert it to exponential notation, i.e. 1.002387123498103e+34.
Then, according to the question about money formatting, you can use the following code:
x.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
It will result in: "10,023,871,234,981,029,898,198,264,897,123,897.231241235".

Categories

Resources