Excel to XML: Round decimals to the nearest hundredth and keep hyperlinks - javascript

I followed this guide to export an Excel Spreadsheet as an XML data file and then this guide to display the XML sheet as an HTML table on my website. It worked great. Now I "only" have to small issues remaining that I couldn't get solved.
(1) The output table contains numbers like 1.325667 but also lots of 0s. I would like the zeroes to be displayed as 0.00 and the numbers with many decimals to be displayed as 1.33. Basically, each number should be displayed with two decimals.
(2) The excel sheet contains hyperlinks to other pages on my website that I would like to keep when rendering the XML data file and then the HTML table. So far, that didn't work. Is this possible?
UPDATE I figured this part out. By breaking up the hyperlinks in just their character-strings, then adding new columns for these character strings, and then tweaking the source code to including
document.write("<tr><td><a href='");
document.write(x[i].getElementsByTagName("character-string")0].childNodes[0].nodeValue);
document.write(".php'>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</a></td>");
I was able to include hyperlinks.
The Excel-Sheet is formatted with these two aspects already integrated, but the conversion to an XML file seems to be the problem.
Thank you so much for your help (again and again :-))
UPDATE I now also found a way to do the rounding in Excel, but I'm still stuck with integers and numbers with only one decimal. Basically, I now "only" need a way to show every number with two decimal points, applying to integers (e.g. 0 should 0.00) and numbers with one decimal (e.g. 1.5 should be 1.50). JohnnyReeves' answer seems to be on the right track but I couldn't get it to work. Any other ideas?

The Number Object has the method toFixed():
1.325667.toFixed(2) = 1.33.
Running inside the loop of the XML, select the URL and add it to the link:
document.write("< a href=" + x[i].getElementsByTagName(< your URL link>) + ">);
document.write("some text");
document.write("< /a>");

The Number.toFixed method will only work on floating point values (eg: 2.1), but not on integers (eg: 2, or 0). You will need to convert your number type to a string type so you can format it for display and get consistent results regardless of the input. A function like this should do the trick:
function formatNumber(value) {
var parts,
trailingDigits,
formattedRemainder;
// Coerce the supplied value to a String type.
value = String(value);
// Break the supplied number into two parts, before and after the dot
parts = value.split(".");
// If there was no dot, there will only be one "part" and we can just
// add the trailing zeros.
if (parts.length === 1) {
formattedRemainder = "00";
}
else {
trailingDigits = parts[1];
if (trailingDigits.length === 0) {
// A dot, but no digits. (eg: 2. -> 2.00)
formattedRemainder = "00";
}
else if (trailingDigits.length === 1) {
// Add an extra trailing zero (eg: 2.1 -> 2.10)
formattedRemainder = trailingDigits + "0";
}
else {
// Just take the last two trailing digits.
formattedRemainder = trailingDigits.substring(0, 2);
}
}
// Build the final formatted string for display.
return parts[0] + "." + formattedRemainder;
}

Related

JavaScript number formatting with point for thousand and comma for decimals

I have a web application with some calculations in text fields. Application is worked in asp.net using vb. I have JavaScript that need to do some calculations every time onTextChange action.
For example I have to enter a number in this format 123.123 or 123 and at the end I want to calculate all text fields and to do formatting like this 123.123,00 or 123,00
For now I am using:
document.getElementById('<%=FV.FindControl("txtSUM").ClientID%>').value = ("" + sum).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function ($1) { return $1 + "." });
but this only adding a point on thousand, apart from that I want to add and comma on decimal place.

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 to set automatically decimal values using javascript

I want to change the number into integer and decimal portions after specific length. For example if I am entering more than 8 digit balance digits should be displayed as decimal values.
input :
4567454857
output:
45674548.57
Javascript Numbers without a decimal portion (ie, they look like ints) can be easily converted to decimals through division (JS isn't like other languages where ints can't become floats). However, for your problem, I have a solution involving substrings and the ability to convert freely between Number and String.
function truncateToEightDigits(num) {
if (num > 99999999) { // if num has more than 8 digits
var str = String(num);
return Number(str.substr(0, 8) + '.' + str.substr(8, str.length));
} else {
return num;
}
}
This also has the added benefit of avoiding weird issues with floating point math you might incur if you tried to do something such as divide by 10 repeatedly.
Side note: I'm not really sure what this has to do with ASP.NET and I'm kinda wondering why you tagged your question with that.

Javascript Regex for Decimal Numbers - Replace non-digits and more than one decimal point

I am trying to limit an input to a decimal number. I'd like any invalid characters not to be displayed at all (not displayed and then removed). I already have this implemented but for whole integers (like input for a phone number) but now I need to apply it for decimal input.
Sample input/output:
default value 25.00 -> type 2b5.00 -> display 25.00
default value 265.50 -> type 2.65.50 -> display 265.50 (as if prevented decimal point from being entered)
default value 265.52 -> type 265.52. -> display 265.52 (same as previous one)
End New Edit
I found many threads that dealt with "decimal input" issue but almost 99% of them deal only with "match"ing and "test"ing the input while my need is to replace the invalid characters.
Other than trying many regexes like /^\d+(\.\d{0,2})?$/, I also tried something like the below which keeps only the first occurrence in the input. This still isn't my requirement because I need the "original" decimal point to remain not the first one in the new input. This was the code for it:
[this.value.slice(0, decimalpoint), '.', this.value.slice(decimalpoint)].join('')
This thread is the closest to what I need but since there was no response to the last comment about preventing multiple decimal points (which is my requirement), it wasn't useful.
Any help would be appreciated.
Outline: find the first ., split there and clean the parts, else just return cleaned value.
function clean(string) {
return string.replace(/[^0-9]/g, "");
}
var value = "a10.10.0";
var pos = value.indexOf(".");
var result;
if (pos !== -1) {
var part1 = value.substr(0, pos);
var part2 = value.substr(pos + 1);
result = clean(part1) + "." + clean(part2);
} else {
result = clean(value);
}
console.log(result); // "10.100"

Round number to two decimal places and delete any other decimal points

I have a javascript function that grabs some data from the current webpage the user is one, one thing it grabs is the contents of a element with the class name 'price'.
Currently I use:
price = price.replace(/[^\d.]/g, "");
Which will strip away anything else other than a number and decimal points from what was within the element (in theory leaving just the actual price). Most of the time this works well and you are left with something like 20.99 when the element had <br/>20.99 Is the price for example.
This works pretty well however on some websites what is left is actually a string with more than one decimal point so something like:
20.9999393.9374.028
What I need to then do is strip away everything after two decimal places after the first decimal point so the above would become
20.99
try this:
var price = "20.9999393.9374.028";
var nums = price.split(".");
var num = nums[0] + '.' + nums[1].substr(0,2);
DEMO

Categories

Resources