将十进制数转换为分数/有理数 [英] Convert a decimal number to a fraction / rational number

查看:221
本文介绍了将十进制数转换为分数/有理数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,有没有办法将十进制数字(例如 0.0002 )转换为表示为字符串的分数(例如 2/10000)?

In JavaScript, is there any way to convert a decimal number (such as 0.0002) to a fraction represented as a string (such as "2/10000")?

如果编写了一个名为 decimalToFraction 的函数这个目的,然后 decimalToFraction(0.0002)将返回字符串2/10000

If a function called decimalToFraction had been written for this purpose, then decimalToFraction(0.0002) would return the string "2/10000".

推荐答案

您可以使用Erik Garrison的分数.js 库可以做更多的分数操作。

You can use Erik Garrison's fraction.js library to do that and more fractional operations.

var f = new Fraction(2, 10000);
console.log(f.numerator + '/' + f.denominator);






要做.003你可以做到


To to do .003 you can just do

var f = new Fraction(.003);
console.log(f.numerator + '/' + f.denominator);

这篇关于将十进制数转换为分数/有理数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆