PHP发邮件标题与内容乱码的解决方法

先用函数base64_encode() — 使用 MIME base64 对数据进行编码
标题字符串前加编码类型例如: =?UTF-8?B?
标题字符串后加:?=
邮件header指明Content-type: text/html; charset=utf-8,这样就能防止邮件正文乱码

$to         = ‘zhoz@example.com’;
$subject   = “=?UTF-8?B?”.base64_encode(‘邮件标题’).”?=”;
$headers   = ‘MIME-Version: 1.0′ . “\r\n”;
$headers .= ‘Content-type: text/html; charset=utf-8′ . “\r\n”;
// Additional headers
$headers .= ‘To: zhoz <zhoz@example.com>’ . “\r\n”;
$headers .= ‘From: Admin <admin@example.com>’ . “\r\n”;
$headers .= ‘Reply-To: zhoz <zhoz@example>’ . “\r\n”;
mail($to, $subject, $message, $headers);
Posted in PHP | Tagged , | 2 Comments

去掉IE和Firefox点击链接时的焦点虚线框

IE里需要在 a 标签中加入 hidefocus=”true” 属性:<a href=”” hidefocus=”true” title=””>siteface</a>
而在Firefox等浏览器中定义CSS:a { outline:none; }或者a { outline:0; } 就可以了。

在IE里 hideFocus即隐藏聚焦,具有使对象聚焦失效的功能,其功能相当于:
onFocus=”this.blur()”
它的值是一个布尔值,如hideFocus=true。也可省略赋值直接写hideFocus。

Posted in IE, css | Tagged , , | Leave a comment

PHP 错误之引号中使用变量

当看到错误提示
syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING
这个提示,是提示变量使用的问题。
而我出现的是,语句中使用了数组,导致失败。下面看看失败的代码;
<?php
echo “我是数组,$n['x']“;
?>
这样即时双引号是可以解析变量的,但是素组这样的,写法是没办法解析。修改成下面就可以了!
<?php
echo “我是数组,{$n['x']}”;
?>
加上花括号{}可以让语句识别这里面是动态的。

Posted in PHP | Tagged | 1 Comment

Smarty 定界符 花括号 大括号 函数定义 转义

使用 Smarty 模板的时候,通常都是用 ‘{’ 和 ‘}’ 作为定界符(delimiter)。

有时,我们需要在 html 代码里输出大括号,如果在模板里直接写出来,会被 Smarty 的解析器认为是定界符,然后会报错:

Smarty error : syntax error: unrecognized tag

无法识别的标签!

如何解决呢?有 2 种办法:

1:内置变量

ldelim, rdelim
ldelim and rdelim are used for displaying the literal delimiter, in our case “{” or “}”. The template engine always tries to interpret delimiters, so this is the way around that.

ldelim 和 rdelim 用于输出分隔符,也就是大括号 ‘{’ 和 ‘}’。如果只是输出很少的几个大括号,请使用此方法。

2: 文本转义

我们经常会在 html 里写 javascript 函数,就不可避免地写大量的大括号,这个时候上面的解决方法就不适用了,Smarty 提供了一个转义一段代码的标签:{literal}…{/literal}

{literal}
<script type=”text/javascript”>
function sayHello() {alert(‘Hello World!’)}
</script>
{/literal}

这样,就可以在里面随意写各种符号,不必担心 Smarty 引擎会错误解析了!

Posted in zf+smarty | Tagged | Leave a comment

sql server 2005 存储过程分页

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
名称:PagingRecord
作用:按任意字段进行排序分页
*/


CREATE    PROCEDURE [dbo].[PagingRecord]
(
@PageIndex int,--页号,从0开始
@PageSize int,--页尺寸
@OrderField varchar(100),--排序字段及类型(多个条件用逗号分开)如:JobID DESC,Checkintime
@TableName varchar(100),--表名或视图表
@StrWhere varchar(2000),--条件
@FieldList varchar(2000),--欲选择字段列表
@DoCount  AS bit=1-- 0值返回记录总数, 非 0 值则返回记录
)
AS

BEGIN TRAN

DECLARE @SqlQuery varchar(4000)

IF @DoCount&lt;&gt;0
Goto GetCount
Else
Goto GetSearch

GetCount:--返回记录总数
DECLARE @SearchSql AS Nvarchar(4000)
SET @SearchSql= 'SELECT Count(*) AS Total FROM <a href="mailto:%20+@TableName+%20">'+@TableName+'</a> WHERE <a href="mailto:%20+@StrWhere">'+@StrWhere</a>
exec sp_executesql @SearchSql
--print @SearchSql
COMMIT TRAN
RETURN

GetSearch:

SET @SqlQuery='SELECT <a href="mailto:%20+@FieldList+%20">'+@FieldList+'</a>
FROM (SELECT row_number() over(ORDER BY <a href="mailto:%20+@OrderField+%20">'
+@OrderField+'</a>) as rownum,
<a href="mailto:%20+@FieldList+%20">'
+@FieldList+'</a>
FROM <a href="mailto:%20+@TableName+%20">'
+@TableName+'</a> WHERE <a href="mailto:%20+@StrWhere">'+@StrWhere</a> +') as temp
WHERE rownum BETWEEN ('
+cast(@PageIndex AS varchar)+'-1)*'+cast(@PageSize AS varchar)+'+1 and '+cast(@PageIndex

AS varchar)+'*'+cast(@PageSize AS varchar) + ' ORDER BY <a href="mailto:%20+@OrderField">'+@OrderField</a>
--print @SqlQuery
SET NOCOUNT ON
execute(@SqlQuery)
SET NOCOUNT OFF
COMMIT TRAN
Posted in mssql | Tagged | Leave a comment

清除MSSQL事务日志文件的几种方法

1.清空日志

1):打开查询分析器,输入命令
DUMP TRANSACTION 数据库名 WITH NO_LOG
2):再打开企业管理器–右键你要压缩的数据库–所有任务–收缩数据库–收缩文件–选择日志文件–在收缩方式里选择收缩至XXM,这里会给出一个允许收缩到的最小M数,直接输入这个数,确定就可以了。

2.删除LOG

1):分离数据库企业管理器->服务器->数据库->右键->分离数据库
2):删除LOG文件
3):附加数据库企业管理器->服务器->数据库->右键->附加数据库

此法生成新的LOG,大小只有500多K

3、如果想以后不让它增长

企业管理器->服务器->数据库->属性->事务日志->将文件增长限制为2M

再将此数据库设置自动收缩

Posted in mssql | Tagged | Leave a comment

实践小记-多服务器文档同步与将应用程序添加到系统服务中

最近项目中需要实现两台异地服务器图片同步,于是就开始查资料寻找合适的方法或者软件,其中在一篇文章中提到一个软件,WebSynchronizer,介绍是这样的:

档案同步化工具 – WebSynchronizer,由知名续传软件 ReGet 之软件出版公司所推出,是网站同步化、档案镜像、档案备份的绝佳工具,可以执行下列主要工作:

1) 本机资料夹及远程资料夹的同步化;
2) 两台远程计算机中的资料夹同步化;
3) 两个本机资料之同步化。

看介绍正好符合我的需求,于是便搜索这个软件,在BAIDU上搜索的都是1.3版本的,而且非开源软件,这个可愁了,现在不可能花钱去购买软件的,只能再找, 看看有没有破解版本的,结果中文搜索结果都没有破解的,于是又转向GOOGLE,结果不经意之间发现了WebSynchronizer1.5版,而且还有开源代码,难道是免费的?我赶紧下载下来,安装,一路下来也没有提示要输入序列号,就这样安装好了,真是喜出望外,后来看了一下更新日志,原来到1.5版本这个项目转成开源的了:

Current version: WebSynchronizer 1.5 (build 162)

Build 162 / 09 Jan
WebSynchronizer moved to open source

不错不错,界面好,设置简单,功能强大,绝对的好东西啊!

Continue reading

Posted in windows | Tagged , , , | 1 Comment

风声无组件上传类修改版

这次修改的更新主要是增加了对保存目标路径的判断,如果不存在,就自动生成,SavePath的参数支持相对路径和绝对路径
uploadclass
下面把代码贴出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
'----------------------------------------------------------
'****************  风声无组件上传类 2.11  *****************
'作者:风声
'网站:http://www.fonshen.com
'邮件:webmaster@fonshen.com
'版权:版权全体,源代码公开,各种用途均可免费使用
'修改:迦楠
'网站:http://www.ishere.cn | http://www.aobodo.com
'说明:SavePath参数支持相对与绝对两种路径,并自动生成目标文件夹
'**********************************************************
'----------------------------------------------------------
Class UpLoadClass

Private m_TotalSize,m_MaxSize,m_FileType,m_SavePath,m_AutoSave,m_Error,m_Charset
Private m_dicForm,m_binForm,m_binItem,m_strDate,m_lngTime
Private m_Fso,astrPath, ulngPath, i, strTmpPath
Public  FormItem,FileItem

Public Property Get Version
Version="Fonshen UpLoadClass Version 2.11"
End Property

 <a href="http://ishere.cn/2008/12/01/%e9%a3%8e%e5%a3%b0%e6%97%a0%e7%bb%84%e4%bb%b6%e4%b8%8a%e4%bc%a0%e7%b1%bb%e4%bf%ae%e6%94%b9%e7%89%88.html#more-463" class="more-link">Continue reading <span class="meta-nav">&rarr;</span></a>
Posted in ASP | Tagged , | Leave a comment

IE6.0及以下版本PNG透明图片不透明解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
Correctly handle PNG transparency in Win IE 5.5 &amp; 6.
Copyright 2007 Ignia, LLC
Based in part on code from from http://homepage.ntlworld.com/bobosola.
Edit: Jena.want
Date: 2008.11.30
Web: www.AOBODO.com | www.IsHere.cn

Use in  with DEFER keyword wrapped in conditional comments:

<!--[if lt IE 7]>
<mce:script defer type="text/javascript" src="pngfix.js" mce_src="pngfix.js"></mce:script>
<![endif]-->
*/


(function fixPng() {
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

if ((version &gt;= 5.5 &amp;&amp; version &lt; 7.0) &amp;&amp; (document.body.filters)) {
for(var i=0; i
var img = document.images[i];
var imgName = img.src.toUpperCase();
if (imgName.indexOf(".PNG") &gt; 0) {
var width = img.width;
var height = img.height;
var sizingMethod = (img.className.toLowerCase().indexOf("scale") &gt;= 0)? "scale" : "image";
img.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.src.replace('%23', '%2523').replace("'", "%27") + "', sizingMethod='" + sizingMethod + "')";
img.src = "images/blank.gif";
img.width = width;
img.height = height;
}
}
}
})();

这是打好包的文件,需要的朋友可以下载试试。msiepng

另外,如果PNG图片做背景的话,在IE6下也会出现不透明情况,以上脚本只解决了页面中的PNG图片透明,如果是CSS样式中使用了透明的PNG图片,则可以使用以下方案解决:

1
2
3
4
5
#png {
background: url(绝对路径/images/bg.png) repeat;
_filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='scale', src="绝对路径/images/bg.png");
_background:none;
}
Posted in IE, css, javascript | Tagged , , | 1 Comment

BUY.MaiMaiJ.com-基于买卖街批发订单管理系统的新型B2C网站!

buy.maimaij.com

Buy.MaiMaiJ.com is a professional wholesale website in China, dedicating itself to build a worldwide wholesale shop online.

Our site is aiming to operate the B-to-C transactions with consumers from all over the world. The biggest superiority of our site is applying the system MaiMaiJ (http://www.MaiMaiJ.com), It can provide global sellers and buyers with easier methods for processing and managing wholesale orders.

Our slogan is “Buy Wholesale Products from Chinese Wholesaler”, using Buy.MaiMaiJ.com, the buyers can submit orders online and the sellers manage orders easily, without handwork, Emails and Faxes.

You can get what you like on this website at wholesale prices. We sell a vast range of merchandise produced exclusively by Chinese manufacturers. If you like to hunt for something special at low price by fashionable online shopping, then use Buy.MaiMaiJ.com to purchase various kinds products you are interested in.

http://buy.maimaij.com/links.html

http://buy.maimaij.com/links-add.html

Posted in 买卖街 | Tagged | Leave a comment

JS判断客户端是否安装了MSN,Skype,QQ软件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
/*
 * author:Jena.want
 * web:www.AOBODO.com
 * last edit:2008.11.11
 * 谨以此送给正在享受光棍节的哥们们!祝今年节日快乐!祝明年不再过此节!
 */
  //<![data[
checkInstalled = function(m) {
    switch(m){
        case 'msn':
            try {
                new ActiveXObject("MSNMessenger.P4QuickLaunch");
                return true;
            }
            catch (e) {
                return false;
            }
        case 'skype':
            try{
                new ActiveXObject("Skype.Detection");
                return true;
            }catch(e){
                return false;
            }
        case 'qq':
     try {
                new ActiveXObject("TimwpDll.TimwpCheck");
                return true;
     }
     catch (e) {
                return false;
     }
    }
}  //]]-->
  </script>
<input type="button" value="检测有没有安装MSN" onclick="alert(checkInstalled('msn'))" />
<input type="button" value="检测有没有安装QQ" onclick="alert(checkInstalled('qq'))" />
<input type="button" value="检测有没有安装SKYPE" onclick="alert(checkInstalled('skype'))" />
</body>
</html>

测试环境:WIN SERVER 2008,IE6+,Firefox2.0+,Opera,Chorme

Posted in javascript | Tagged , , , | 2 Comments

PclZip简介与使用[转]

PclZip介绍
PclZip library能够压缩与解压缩Zip格式的压缩档(WinZip、PKZIP);且能对此类类档案进行处理,包括产生压缩档、列出压缩档的内容以及解压缩档案等等。由于能够在伺服器端进行压缩与解压缩的动作,所以相当方便使用。
PclZip定义一个PclZip类别,其类别物件可视为一个ZIP档案,亦提供method来进行处理。

如何使用PclZip
1.基础
所有的功能都由pclzip.lib.php这个档案提供,PclZip library可于其首页(www.phpconcept.net/pclzip/index.en.php)下载,(PS:但是目前打不开了,我上传了一个文件class-pclzip)。所有的PKZIP档案其实就是一个 PclZip的类别物件。当产生一个PclZip档案(ie, PclZip类别物件),就会先产生一个压缩档,且档名已经指定,但此压缩档的内容尚未存在:


< ?PHP
require_once('pclzip.lib.php');
$archive = new PclZip("archive.zip");
?>

此物件提供了一些public method可用来处理此档案。
Continue reading

Posted in keyboard's joy | Tagged , , | Leave a comment

PHP读取MSSQLSERVER数据库image字段,突破4096限制

以前的程序是把图片通过ASP以二进制的格式存储到MSSQLSERVER中的,现在需要用PHP把它显示出来,

$id = $_GET['id'];
$conn = dbo_connect();
$query = “select f.Data from Files f,Products p where p.PhotoSN=f.SN and p.ID=$id”;
$result = mssql_query($query, $conn);
if (mssql_num_rows($result)) {
$row = mssql_fetch_assoc($result);
if (!empty($row['Data'])) {
echo $row['Data'];
}
}
mssql_close($conn);

但是读取出来的图片都只有开头一小部分,其它部分是空白,全选以后看到的图片大小似乎也是正常的,就是有一部分显示不出来,好一个纳闷。质量高的图片显示的部分还要小,质量低的或者图片尺寸小的就要显示的多一些,看样子是读取的数据大小是一致的。后来一看$row['Data']的长度,果然清一色的4096,原来如此。
上网查资料,费了好大劲,才看到一句有价值的话“是配置错了”。配置错了?难道PHP读取MSSQL的image数据还有大小限制?赶紧打开php.ini,搜索image,没有相关的,搜索4096,还没有相关的,不会吧?!哈哈,原来是已经搜索到文件末尾,还在向下搜索,难怪没有。赶紧改方向,找到了!但是无关,再搜,OK,终于找到了:

; Valid range 0 – 2147483647. Default = 4096.
;mssql.textlimit = 4096

; Valid range 0 – 2147483647. Default = 4096.
;mssql.textsize = 4096
原来如此,把mssql.textlimit和mssql.textsize后面的值都改成最大,2147483647,然后再把前面的分号去掉,保存,重启IIS。再去看刚才的程序显示出来的图片,成了,全部显示!
真亲啊!GOOD!

Posted in keyboard's joy | Tagged , | Leave a comment

让你的VB6.0 IDE支持鼠标滚轮[转]

这年头估计用VB6做开发的人已经不多了吧。公司有个项目,需要用到VB6,每次都为在编辑器里不能滑动滚轮而烦恼,实在是不方便啊,也难怪,有点年头了。今天在网上找资料,碰巧看到一篇文章就是解决这个问题的,呵呵,太好了。操作步骤如下:

1、下载http://download.microsoft.com/download/e/f/b/efb39198-7c59-4ace-a5c4-8f0f88e00d34/vb6mousewheel.exe,这是一个自解压的包,其中包含VB6IDEMouseWheelAddin.dll和其源程序,或者在附件里下载,我已经上传了,vb6idemousewheeladdin-dll

2、将包中的VB6IDEMouseWheelAddin.dll或者将源程序编译出一个新的VB6IDEMouseWheelAddin.dll COPY到系统目录或者VB安装目录(防止被删除)。

3、运行regsvr32 <path>\VB6IDEMouseWheelAddin.dll,注册这个dll。

4、运行Visual Basic 6.0。

5、单击“外接程序”菜单下的“外接程序管理器”,弹出“外接程序管理器”对话框。

6、在“可用外接程”序列表中,选择“MouseWheel Fix”,在加载行为栏中单击选中“加载/卸载和在启动中加载”复选框。

7、确定,完成。

这时,你的Visual Basic6.0 IDE已经支持滚轮了

Posted in keyboard's joy | Tagged , | Leave a comment

php读取 mssql数据datatime时间字段的问题

mssql默认以系统时间格式输出,你可以调整系统的时间格式来解决

当然是在程序里解决比较灵活,例如:

“select  convert(char,日期字段,120)   as   date2   from   table”

convert(char,date,N)输出的各中样式
N 日期样式
0 04 2 2005 9:06AM
1 04/02/05
2 05.04.02
3 02/04/05
4 02.04.05

Continue reading

Posted in keyboard's joy | Tagged , , | Leave a comment

IE6下 location.href BUG

代码如下:
<script type=”text/javascript”>
loadURL = function(){
location.href = “http://www.aobodo.com”;
}

</script>
<a href=”javascript:void(0);” onclick=”javascript:loadURL();”>Link1</a>
<a href=”#” onclick=”javascript:loadURL();”>Link2</a>
<a href=”javascript:loadURL();”>Link3</a>

以上三种方式在IE7+,Firefox下可以正常执行,第一种方式在IE6-没有响应。

第一种方式要想在IE6-下正常执行,需要修改成<a href=”javascript:void(0);” onclick=”javascript:loadURL();return false”>Link1</a>。

Posted in IE, javascript | Leave a comment

买卖街又添新服务了!:)

买卖街本着“用户至上”的服务原则,从用户的实际需要出发,增加了更多人性化的贴心服务。为了方便您更加流畅地使用买卖街,也为了买卖街能更好地为您服务,我们特设立了QQ讨论群,实现了我们与您的实时交流,解答您在使用过程中遇到的问题,听取您对买卖街的意见和建议;同时您还可以与其他用户交流使用买卖街的心得。
加入QQ 讨论群,畅所欲言买卖街!让我们了解您的心声,您的需求就是我们的追求!
群号:55200511

Posted in 买卖街 | Leave a comment

快速使用CoolCode-WordPress代码着色插件

第一次发布还失败了,原因是代码里有coolcode标签,结果让编辑器给替换了 :( 再发一次,这次把coolcode标签替换成mycodes,实际使用中要替换回来。

今天为WP增加了一个插件CoolCode,作用就是让内容里的代码能够高亮显示,经常写些程序代码,但是以前只是普通的文字,没有相应的颜色,有了这个插件,写出来的代码加上颜色,就好看多了。

经过测试,在编辑器Visual模式下写的代码不能被正常的的解析,只有在HTML模式下写出来的代码才能被正常的解析到。然而每次都要写上<mycodes lang=”javascript”></mycodes>,虽然字数不多,但是像这样简单的代码就懒得写了,于是,决定在HTML模式下,增加一个快捷按钮,就像已有的link,code一样,点击一下,输入几个参数就可以了。

CoolCode有三个参数,lang,指定被包含的程序代码是哪种语言,支持actionscript cpp css diff dtd html java javascript mysql perl php python ruby sql xml;linenum,指定是否显示行号,值是true或者false,默认是true;download,指定要下载的文件的路径加文件名。这三个参数都是可选的。了解了这些,就开始写代码了。

首先是在“\wp-includes\js\quicktags.js”里进行修改,
添加要显示的按钮:

edButtons[edButtons.length] =
new edButton(‘ed_coolcode’
,’mycodes’
,”
,’</mycodes>’
);

将这个按钮增加到“edShowButton”函数里:

function edShowButton(button, i) {
if (button.id == ‘ed_img’) {
document.write(‘
‘);
}
else if (button.id == ‘ed_link’) {
document.write(‘
‘);
}
else if(button.id == ‘ed_coolcode’) {
document.write(‘
‘);
}
else {
document.write(‘
‘);
}
}

因为这个按钮需要接收弹出框的信息,所以要单独写。 Continue reading

Posted in keyboard's joy | Tagged | 1 Comment

HMailServer-免费邮件服务器

HMailServer is a free, GNU GPL licensed email server for Windows. It runs as a service with a management tool that connects to allow configuration of settings similar to the way Exchange works. It has support for the IMAP, POP3, and SMTP open email standard protocols, and stores index data in MySQL or MS SQL but the actual e-mail content is still stored as files in a format similar to Maildir (the contents are the same but the directory structure is different). It is updated frequently and has active support and development forums.

All common features such as multiple-domain support, aliases (catch-all and specific ones for addresses and also for domains themselves) and basic mailing lists are present. Users can be authenticated against both the local system and other servers, including domain controllers.

It offers a variety of anti-spam options such as:-

  • Host based DNS Blacklisting (DNSBL)
  • URL based DNS blacklisting (SURBL)
  • Greylisting (must retry sending for the message to succeed)

And provides basic support for using JScript or VBScript to modify the behaviour of the server on receipt of messages and at a variety of other events (including client connection).

HMailServer in current versions does not include SSL or TLS support, however this can be easily added using a third party application called STunnel which uses the OpenSSL libraries to add secure connection support. IPv6 support can also be added using STunnel, it is not included.

There is recent discussion that further releases of the software will not be open source visible on the forums by the developer.

Some features that may be of interest to businesses but are commonly missing in other servers are also available and easy to configure, such as:-

  • Compulsory signatures (for legal and advertising footers)
  • Server side rules
  • External account retrieval
  • Quotas on domain, mailbox, and individual message sizes
  • Plus addressing (using + to make a virtual alias for an account specific to a task, as seen in Gmail)
  • Attachment blocking
  • E-Mail mirroring (all messages sent to a particular address)
  • Custom SMTP routes for specific domains

Integration is supported for many related applications, including:-

  • SquirrelMail for webmail, (requires IIS or Apache); spell-checking available
  • ClamAV anti-virus software
  • SpamAssassin spam filtering
  • and more…
Posted in keyboard's joy | Tagged , , , , | 1 Comment

JS jscript做小数乘法运算出现浮点错误的解决办法

在Javascript里计算小数乘法,容易出现浮点错误,例如:

1
2
3
4
5
<script>
document.write (1.1*1.3);
document.write ("<br>");
document.write (1.2*1.1);
</script>

输出结果:

1
2
1.4300000000000001
1.32

解决问题的思路就是,先把因数放大为整数,最后再除以相应的倍数,这样就能得到正确的结果了。解决办法如下:
1、 在算式中解决

1
2
3
<script>
alert(1.1*(1.3*10)/10)
</script>

2、添加到Number的原型方法里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
Number.prototype.rate=function(){
var oStr=this.toString();
if(oStr.indexOf(".")==-1)
return 1;
else
return Math.pow(10,parseInt(oStr.length-oStr.indexOf(".")-1));
}
function tran(){
args=tran.arguments;
var temp=1;
for(i=0;i < args.length;i++)
temp*=args[ i ]*args[ i ].rate();
for(i=0;i < args.length;i++)
temp/=args[ i ].rate();
return temp;
}
</script>

使用方法:假如11*22.9,可以这样写tran(11,22.9),这样,问题就解决了。

Posted in javascript | Tagged , , , | 1 Comment