Thread: How to return this script to 2 decimals with no rounding

1. Registered User
Join Date
Apr 2016
Posts
4

How to return this script to 2 decimals with no rounding

The following is from a javascript form located at http://source-pro.org/PPT-Calc.html

obj.res3.value =h3;
obj.res4.value =h4;
obj.sres3.value =s3;
obj.sres4.value =s4;

I need each value to return to only 2 decimals with no rounding.

Ideas?

2. Are you asking for the output value to be truncated two digits after the decimal?

3. Registered User
Join Date
Apr 2016
Posts
4
Yes - thank you for making this clearer!

4. Consider this then...

Code:
```<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />

<title> HTML5 page </title>

</head>
<body>
<pre id="debug"></pre>

<script type="text/javascript">
var vals = [1/3, 2/3, 3/3, 1/4, 2/4, 3/4, 4/4];
var tmp = 0;

var str = 'Value display\n';
for (var i=0; i<vals.length; i++) { str += vals[i]+'\n'; }
str += '\nValue display using .toFixed(2) [Note: rounds]\n';
for (var i=0; i<vals.length; i++) { str += vals[i].toFixed(2)+'\n'; }
str += '\nValue display using .toFixed(3) [Note: rounds]\n';
for (var i=0; i<vals.length; i++) { str += vals[i].toFixed(3)+'\n'; }

str += '\nValue display using .toFixed(3) then truncates\n';
for (var i=0; i<vals.length; i++) {
tmp = vals[i].toFixed(3);
str += tmp.substr(0,tmp.length-1)+'\n';
}

document.getElementById('debug').innerHTML = str;

</script>

</body>
</html>```

5. Registered User
Join Date
Apr 2016
Posts
4
I appreciate your help but to be honest I am unclear as to implement your solution.

I apologize for my lack of javascript knowledge.

6. Registered User
Join Date
Sep 2014
Posts
2
What his code is doing is rounding the number to 3 decimal places, saving that value to tmp and then removing the last digit from tmp

tmp = number.toFixed(3);
str = tmp.substr(0,tmp.length-1)

7. Registered User
Join Date
Apr 2016
Posts
4
Got it!

Thank you two for your help!

8. The traditional way of teaching on truncation from when I was at school, college & night school...

Using the following example
Code:
```var x = 123.456789; // the number to truncate
console.log("The number     : " + x);
var y = x.toFixed(2); // not recommended by lots of sources because of spurious rounding
var z = Math.floor( x * 100 ) / 100; // the time honoured way
var x = x.toString(); // convert to a string
x = x.slice(0, x.indexOf( ".") + 3 ); // find decimal and move two places to right
console.log("toFixed        : " + y);
console.log("traditional    : " + z);
console.log("unconventional : " + x);```
outputs the following
Code:
```The number     : 123.45678901
toFixed        : 123.46
traditional    : 123.45
unconventional : 123.45```
You can see how toFixed rounds up values, Math.floor is used to ensure that the 3rd value has no impact on the truncation value, IMHO taking the value, making it a string and slicing out your value is a better option, it can be cast back in to a number by subtracting zero.
x = x - 0; or as some others would say is a better option, x = x * 1; which I was taught that in computers addition and subtraction is much faster than multiplication or division because they only add multiples and take longer processing times.

9. Registered User
Join Date
Sep 2007
Posts
390
Code:
```
<script type="text/javascript">

Number.prototype.ondalikBasamak= function(n){

// alert("this = "+this);// 123.45678901

var A = String(this).split('');// diziye dönüştü
// alert("A="+ A);
// alert(A.splice(A.indexOf('.')+n+1,A.length)); // diziden ayrılan kısım
A.splice(A.indexOf('.')+n+1,A.length);

return Number( A.join(''));
}
var num=123.45678901;

alert(num.ondalikBasamak(2));

var m = Math.random();
alert("m="+m);
alert(m.ondalikBasamak(4));
alert(987.54321.ondalikBasamak(3));

//http://www.w3schools.com/js/js_array_methods.asp
// This code is working firefox 34.05
</script>```
Last edited by Ayşe; 04-20-2016 at 12:03 PM.

10. Simple and easy to understand
Code:
```Number.prototype.trunc = function( d ){
d++;
var tmp = (""+this);
return tmp.slice(0,tmp.indexOf(".")+d);
}```
or a bit more tricky...

to get a number
Code:
```Number.prototype.truncate = function( d ){
return (String(this).match(new RegExp("\\d+(\\.\\d{1,"+d+"})?") )[0])-0;
}```
or
to get a string that preserves any trailing zeros.
Code:
```Number.prototype.truncate = function( d ){
return String(this).match(new RegExp("\\d+(\\.\\d{1,"+d+"})?") )[0];
}```
is another way of looking at this issue of returning a truncated number, the RegExp credit partly goes to time thrashing ideas about elsewhere on the internet.

11. Registered User
Join Date
Jul 2011
Posts
26
document.write(num.toFixed(2);

12. Originally Posted by attaboy
document.write(num.toFixed(2);
.toFixed has been covered, you have to remember that it will do rounding up as per my example earlier.

13. Registered User
Join Date
Sep 2007
Posts
390
replace
Code:
```
<script type="text/javascript">

Number.prototype.decimal = function( d ){
return (String(this).replace(String(this).slice(String(this).indexOf('.')+d+1),""));

}
var num=123.45678901;
// alert(typeof  num.toFixed(3)  ); // string
//http://www.w3schools.com/js/js_type_conversion.asp

alert(num.decimal(2));

</script>```
slice
Code:
```
<script type="text/javascript">

Number.prototype.decimal = function( d ){
return (String(this).slice(0,String(this).indexOf('.')+d+1) );

}
var num=123.45678901;

alert(num.decimal(2));

</script>```
Last edited by Ayşe; 04-22-2016 at 01:15 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

"

"

X vBulletin 4.2.2 Debug Information

• Page Generation 0.15036 seconds
• Memory Usage 2,979KB
• Queries Executed 13 (?)
More Information
Template Usage (34):
• (1)SHOWTHREAD
• (1)ad_footer_end
• (1)ad_footer_start
• (1)ad_global_above_footer
• (1)ad_global_below_navbar
• (1)ad_global_header1
• (1)ad_global_header2
• (1)ad_navbar_below
• (1)ad_showthread_firstpost_sig
• (1)ad_showthread_firstpost_start
• (1)ad_thread_first_post_content
• (1)ad_thread_last_post_content
• (9)bbcode_code
• (1)bbcode_quote
• (1)footer
• (1)forumjump
• (1)forumrules
• (1)gobutton
• (1)header
• (1)headinclude
• (1)headinclude_bottom
• (13)memberaction_dropdown
• (1)navbar
• (4)navbar_link
• (1)navbar_moderation
• (1)navbar_noticebit
• (1)navbar_tabs
• (2)option
• (13)postbit
• (13)postbit_onlinestatus
• (13)postbit_wrapper
• (1)spacer_close
• (1)spacer_open
• (1)tagbit_wrapper

Phrase Groups Available (6):
• global
• inlinemod
• postbit
• posting
• reputationlevel
• showthread
Included Files (26):
• ./showthread.php
• ./global.php
• ./includes/class_bootstrap.php
• ./includes/init.php
• ./includes/class_core.php
• ./includes/config.php
• ./includes/functions.php
• ./includes/functions_navigation.php
• ./includes/class_friendly_url.php
• ./includes/class_hook.php
• ./includes/class_bootstrap_framework.php
• ./vb/vb.php
• ./vb/phrase.php
• ./includes/functions_facebook.php
• ./includes/functions_calendar.php
• ./includes/functions_bigthree.php
• ./includes/class_postbit.php
• ./includes/class_bbcode.php
• ./includes/functions_reputation.php
• ./includes/functions_notice.php
• ./packages/vbattach/attach.php
• ./vb/types.php
• ./vb/cache.php
• ./vb/cache/db.php
• ./vb/cache/observer/db.php
• ./vb/cache/observer.php

Hooks Called (71):
• init_startup
• friendlyurl_resolve_class
• init_startup_session_setup_start
• database_pre_fetch_array
• database_post_fetch_array
• init_startup_session_setup_complete
• global_bootstrap_init_start
• global_bootstrap_init_complete
• cache_permissions
• fetch_threadinfo_query
• fetch_threadinfo
• fetch_foruminfo
• load_show_variables
• load_forum_show_variables
• global_state_check
• global_bootstrap_complete
• global_start
• style_fetch
• global_setup_complete
• showthread_start
• showthread_getinfo
• strip_bbcode
• friendlyurl_clean_fragment
• friendlyurl_geturl
• forumjump
• cache_templates
• cache_templates_process
• template_register_var
• template_render_output
• fetch_template_start
• fetch_template_complete
• parse_templates
• fetch_musername
• notices_check_start
• notices_noticebit
• process_templates_complete
• friendlyurl_redirect_canonical
• showthread_post_start
• showthread_query_postids
• showthread_query
• bbcode_fetch_tags
• bbcode_create
• showthread_postbit_create
• postbit_factory
• postbit_display_start
• postbit_imicons
• bbcode_parse_start
• bbcode_parse_complete_precache
• bbcode_parse_complete
• postbit_display_complete
• memberaction_dropdown
• tag_fetchbit
• tag_fetchbit_complete
• forumrules
• navbits
• navbits_complete
• build_navigation_data
• build_navigation_array
• check_navigation_permission
• process_navigation_links_start
• process_navigation_links_complete
• set_navigation_menu_element
• build_navigation_menudata
• build_navigation_listdata
• build_navigation_list
• set_navigation_tab_main
• set_navigation_tab_fallback
• navigation_tab_complete
• fb_like_button
• showthread_complete
• page_templates