ParseFloat Confusion - javascript

In my code, I have this:
<script language="javascript">
function addNumbers()
{
var collect = parseFloat(document.getElementById("Collect").value);
var current = parseFloat(document.getElementById("Current").value);
var Balance = document.getElementById("Bal");
Balance.value = collect + current;
}
</script>
If, for example,the input is: 123.12 + 12.22, the Balance is 135.34
But if the input is : 123.00 + 12.00, the Balance is 135 instead of 135.00.
What should I add to achieve the 2nd output sample?
Thanks.

Use ToFixed(2) mdn
(123.00 + 12.00).toFixed(2) //135.00
Also , use || operator.
So :
function addNumbers()
{
var collect = parseFloat(document.getElementById("Collect").value) ||0;
var current = parseFloat(document.getElementById("Current").value) ||0;
var Balance = document.getElementById("Bal");
Balance.value = (collect + current).toFixed(2);
}
Small gotcha :
(9.999 +9.999).toFixed(2) //"20.00"
So how would I solve it ?
simply :
Multiply by 1000 each and then move decimal point.

It sounds like parseFloat() is working correctly but it's the output that isn't quite to your liking. Try using Number's .toFixed() function for formatting:
Balance.value = (collect + current).toFixed(2)
There's some great discussions of formatting currency over on this question: How can I format numbers as money in JavaScript?

Related

How to revert toLocaleString

I need to convert a formatted number to JS default number format.
This is my code:
String.prototype.toJsFloatFormat = function() {
debugger;
var newVal = this;
return newVal;
}
//Example of use
var input = 10000.22; //default js format
var formatted = input.toLocaleString("es"); // result is: 10.000,22
var unformatted = formatted.toJsFloatFormat(); //expected result = 10000.22;
The problem is when I need to get the formatted number (10.000,22) and I make operations with this formatted number (parseFloat(10.000,22) + 1000) I have bad results ( parseFloat(10.000,22) + 1000 = 1010)
thanks in advance.
It's not easy. There's a reason why most of the comments have said "Don't try -
do your calculations on the number itself, not the formatted value".
You need to work out what the decimal and thousand separator characters are. For that, you will need to know which locale the number was converted into.
(1234.5).toLocaleString("es").match(/(\D+)/g);
// -> [".", ","]
Once you have that, you can replace characters in the formatted string.
function unformatString(string, locale) {
var parts = (1234.5).toLocaleString(locale).match(/(\D+)/g);
var unformatted = string;
unformatted = unformatted.split(parts[0]).join("");
unformatted = unformatted.split(parts[1]).join(".");
return parseFloat(unformatted);
}
There is no way of working out the locale - you have to know it and pass it to the function.
no need to reinvent the wheel -
https://github.com/globalizejs/globalize#readme
var input = 10000.22;
Globalize.parseFloat(input );
I did it this way(in my case it was the 'ru' local format, so I did replace the 'space' symbol):
var myNumber = 1000000;
var formated = myNumber.toLocaleString('ru');
var unformated = parseInt(formated.replace(/\s/g, ''));
your case:
var formated = myNumber.toLocaleString('en');
var unformated = parseInt(formated.replace(/,/g, ''));
I did this, that's fine for me
function localeStringToFloat(locale){
if(!locale) return locale
let test=1000
test=test.toLocaleString(undefined,{minimumFractionDigits: 2,maximumFractionDigits: 2});
let separator=test[1]
let decimalSeparator=test[5]
return parseFloat(locale.replaceAll(separator,'').replace(decimalSeparator,'.'))
}
My functions for format and unFormat currency numbers to 'en-US'. I hope helps
function myFormatPrice(num,digits){
return num.toLocaleString('en-US', {maximumFractionDigits:digits});
}
function myUnFormatPrice(formated){
return parseFloat( formated.replaceAll(',','') );
}

Javascript Count numbers

This probably is a very easy solution, but browsing other questions and the internet did not help me any further.
I made a javascript function which will give me a random value from the array with its according points:
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
document.getElementById("Points").innerHTML += punten;
}
I've added a += punten so i can see that it works correctly. It shows me all the point in the div with the id Points.
But what i wanted to do is count it all together so if i were to draw a 4, King and a 10 it should show 24 instead of 41010.
Thanks in advance! And if you're missing any information please let me know
Currently you are just adding strings together, which concatenate (join together) hence why you end up with 41010. You need to grab the current innerHTML (total) and use parseInt() to convert from a string to a number, then add your new cards that have been chosen, then assign this new value to the innerHTML of your element.
Try the following
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
var total = curPoints + parseInt(punten, 10);
document.getElementById("Points").innerHTML = total;
}
More info on parseInt() here
EDIT
I've added this line -
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
Which will try and convert the innerHTML of the "Points" div, but if it is empty (an empty string converts to false) then curPoints will be equal to 0. This should fix the issue of the div being blank at the start.
innerHTML is a string and JavaScript uses + for both string concatenation as numeric addition.
var pointsInHtml = parseInt(document.getElementById("Points").innerHTML, 10);
pointsInHtml += punten;
document.getElementById("Points").innerHTML = punten;
The second parameter 10 of the parseInt method is usually a good idea to keep there to avoid the function to parse it as an octal.
It might be easier to keep a points variable and only at the end put it in the #Points container, that would make the parseInt no longer necessary
innerHTML will be a string, so you need to convert it into an integer prior to adding the card value :)
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1],
curPunten = parseInt(document.getElementById('Points').innerHTML);
document.getElementById("Points").innerHTML = curPunten + punten;
}

ISO duration with Java script

I apologize for the question because I have already posted a similar question, but I would like to know how I can do the following conversion:
PT11H9M38.7876754S
I want to disable seconds and only show hour and minutes 11:09
When I have time displays minutes from 1 to 9, I want to add a 0 in front of number
Tnx in advice...
You could try this:
var str = 'PT11H9M38.7876754S'
match = str.match(/(\d*)H(\d*)M/),
formatted = match[1] + ':' + (!match[2][1] ? 0 + match[2] : match[2]);
console.log(formatted); // => 11:09
"PT11H9M38.78767545".replace(/PT(\d+)H(\d+)M.*/,function(m,a,b) {return a+":"+(b.length<2?"0":"")+b;});
One-liner :p
Since all the nice RegExp stuff is above here is a third solution a bit more expensive in terms of parsing but you may be looking for something different.
You can use the split function to parse the string and extract the portions that you need.
var pt="PT11H9M38.7876754S";
function showtime(s){
var time = s.split('.');
var hours = time[0].split('T')[1].split('H')[0];
var minutes = time[0].split('H')[1].split('M')[0];
return digitize(hours) + ":" + digitize(minutes)
}
function digitize(i){
return (i>9) ? i : "0" + i;
}
alert(showtime(pt)); // 11:09

How do I simplify this repetitive jquery code?

I made a jQuery script that works fine, I'd just like to see if anyone had tips on simplifying it, in particular the beginning part in which variables are defined.
Though I'm really interested in straight code simplification, here's a quick synopsis on what the script actually does:
Looks for links with a class of 'tour' and defines 3 more variations of its href attribute (swapping out a 4-digit number).
Replaces links with a class of 'tour' with different content that substitutes in the additional 4-digit values.
With a.tour replaced, visibility of part of the content is toggled on hover.
And here's the code:
HTML:
Link
JQUERY:
<script>
$(document).ready(function() {
var aud = $('.tour').attr('href');
var usd = $('.tour').attr('href').replace(7838,'8062');
var gbp = $('.tour').attr('href').replace(7838,'8907');
var eur = $('.tour').attr('href').replace(7838,'8914');
$('.tour').replaceWith('<div class="currency"><p>Price & Bookings</p><ul class="currencydd" style="display:none"><li>Australian Dollar (AUD)</li><li>United States Dollar (USD)</li><li>British Pounds (GBP)</li><li>Euros (EUR)</li></ul></div>');
$('.currency').hover(function () {
$('.currencydd').slideToggle("fast");
});
});
</script>
Don't keep using $(".tour") over and over, it is both neater and more efficient to define a variable equal to it. Also, you don't need to keep checking the .attr("href") because once you've stored that value in aud you can use that:
var $tour = $(".tour"),
aud = $tour.attr('href'),
usd = aud.replace(7838,'8062'),
gbp = aud.replace(7838,'8907'),
eur = aud.replace(7838,'8914');
$tour.replaceWith(...);
Note that your code will update (replace) all .tour links using the aud, usd, etc. values from the first .tour link. Is that what you intend, or should it update them individually?
well for starters you could have the following:
var $aud = $('.tour').attr('href'),
$usd = $aud.replace(7838,'8062'),
$gbp = $aud.replace(7838,'8907'),
$eur = $aud.replace(7838,'8914');
var treplace=function(with){ $('.tour').attr('href').replace(7838,with);};
var usd = treplace('8062');
var gbp = treplace('8907');
var eur = treplace('8914');
Even better, you can do something like this if you want lots of currencies
var abbrev=["USD","GBP","EUR"]
var codes=[8062,8907,8924]
var names=["US Dollar","British Pounds","Aussie Dollar"]
var treplace=function(with){ $('.tour').attr('href').replace(7838,with);};
var s='<div class="currency"><p>Price & Bookings</p><ul>';
for(i in abbrev){
//build the rest of the HTML here, using the arrays
}
s+='</ul></div>'
$('.tour').replaceWith(s)
You could also use a 2D array or a custom object instead of three arrays.
2 suggestions:
1: write a function for url transformation
such as
function currencyExchange(srcUrl){
return srcUrl.substring(0,preLength) + rate * Number(src.substring(preLength));
}
2: using javascript template technique to simply the new element construction.
This is not shorter but definitely more optimized and more extensible. Untested:
var href = $('.tour').attr('href'),
items = '',
currency = {
aud : {
name : 'Australian Dollar',
value : 1
},
usd : {
name : 'United States Dollar',
value : 1.05
},
eur : {
name : 'Euros',
value : 0.8
},
gbp : {
name : 'British Pounds',
value : 0.67
}
}
for (var c in currency) {
var num = href.match(/\d+/), // Simple regex, maybe too simple...
conv = Math.ceil(currency[c].value * num),
url = href.replace(num, conv);
items += '<li>' +
'<a href="' + url + '">' +
currency[c].name + ' (' + c.toUpperCase() + ')' +
'</a>' +
'</li>';
}
$('.tour').replaceWith('<div><ul>' + items + '</ul></div>');
$(document).ready(function() {
var ref = $('.tour').attr('href');
function G(t) {return ref.replace(7838, t=='eur'?'8914':t=='usd'?'8062':t=='gbp'?'8907':'7838');}
$('.tour').replaceWith('<div class="currency"><p>Price & Bookings</p><ul class="currencydd" style="display:none"><li>Australian Dollar (AUD)</li><li>United States Dollar (USD)</li><li>British Pounds (GBP)</li><li>Euros (EUR)</li></ul></div>');
$('.currency').hover(function () {
$('.currencydd').slideToggle("fast");
});
});​
FIDDLE

how to split a number in javascript Linux Firefox getting incorrect value, windows show the correct value

how can I split a number into sub digits. I have a number 20:55 n need to split in to two parts as 20 and 55.
var mynumber = 20:55;
var split = mynumber.toString();
document.write("Hour : " + split[0]);
document.write("Minutes : " + split[1]);
but am getting wrong value after toString() function call.
EDIT: 1 This is what I want. This is working fine but only works with windows. In linux Firefox am not getting the correct value in function .. something like 12.200000000000000001 instead of 12.25
<script type="text/javascript">
var myarray = new Array();
myarray = [[12.25, 1],[13.25,1]];
//alert(myarray[0][0]);
func(myarray[0][0]) ;
function func(n) {
var split = n.split(".");
document.writeln("Number : " + n); // Number : 12.25
document.writeln("Hour : " + split[0]); // Hour : 12
document.writeln("Minutes : " + split[1]); // Minutes : 25
}
</script>
Use split() function
var number_array=mynumber.split(":")
On your example
var mynumber = "20:55";
var split = mynumber.split(":");
document.write("Hour : " + split[0]);
document.write("Minutes : " + split[1]);
More on this
http://www.w3schools.com/jsref/jsref_split.asp
You are using split(), a string function, on a number. Use this:
var split = n.toString().split(".");
Works perfectly on Firefox 3.6.3 (and Opera 10.60, and Chromium 5), Ubuntu Linux 10.04.
Use split function
var numSplit = mynumber.split(':');
Then you can access each value using numSplit[0] and numSplit[1]

Categories